LearnFrenzy
Sign in Take a free test

Functions and Default Arguments · Predict the Output · Question 14

Changing *p vs changing p inside a function Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 14 Back to Exercise

What is the output of the following C++ program?

main.cpp
#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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links