Question 14
Back to Exercise
What is the output of the following C++ program?
#include <iostream>
int other = 99;
void change(int* p) {
*p = 10; // changes the caller's variable
p = &other; // changes only the local copy of the pointer
*p = 20;
}
int main() {
int x = 1;
int* q = &x;
change(q);
std::cout << x << ' ' << *q << ' ' << other << '\n';
return 0;
}
- A 10 10 20 Correct
- B 20 20 99
- C 10 20 20
- D 1 1 20
Correct Answer: Option A
The pointer itself is passed by value. Writing through it changes x; redirecting it changes only the function's copy, so q still points to x. The second write changes other.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!