Reputation: 797
Hello I have simple code like this
void func(int &x, int y, int* z){
int a = 3;
int b = 1;
cout << *z << endl;
x = *z + b;
cout << *z << endl;
y = *z + x;
z = &a;
cout << "func: x = " << x << endl;
cout << "func: y = " << y << endl;
cout << "func: *z = " << *z << endl;
cout << "func: a = " << a << endl;
cout << "func: b = " << b << endl;
return;
}
int main(){
int a = 2;
int b = 4;
func(b, a, &b);
cout << "main: a = " << a << endl;
cout << "main: b = " << b << endl;
return 0;
}
And for output I get
4
5
func: x = 5
func: y = 10
func: *z = 3
func: a = 3
func: b = 1
main: a = 2
main: b = 5
So my question is, for what reason the value of *z changes after x = *z + b
because I can't figure it out by myself.
Thank you in advance
Upvotes: 0
Views: 2877
Reputation: 5118
x = *z + b;
changes the value of z because:
- here, x is an int reference pointing to your caller-side variable b
- z is an int pointer containing the address of the same variable b
Therefore, at this point, x and z refer to the same thing.
Therefore, assigning a new value to x means assigning that value to b. Since z points to b, reading z afterwards gives you the value you assigned to x.
You can make sure of this, for instance by writing and comparing the address of x, and the value of z:
cout << "(1) z is: " << z << " - &x is: " &x
// should be the same
z = &a;
cout << "(2) z is: " << z << " - &x is: " &x
// should be the different
In your context, the two values will be identical until you reassign z.
Upvotes: 1
Reputation: 741
When you use & before an argument you give to a method, it becomes not copied but linked to it.
So that:
You change x which is linked to b
z changes corresponding to b's new value, because it's linked to it.
Upvotes: 1
Reputation: 2618
Because you changed it to point to local variable a
z = &a;
Hence when you dereference it, it gives you value of local variable a, which is 3
Upvotes: 0
Reputation: 58909
x
is a reference to the b
in main (not to be confused with the b
in func, which is separate). z
is a pointer to the b
in main. References are basically pointers, but without the *
or &
syntax, and you can't make them point to something else (there's no equivalent to z = &a
for references).
The line:
x = *z + b;
is basically doing:
b_in_main = b_in_main + b_in_func;
because both x
and *z
refer to the same variable.
Upvotes: 2