Skipher Skipher - 2 months ago 4
C++ Question

Why is the value of a variable changed when I did not assign a new value to it?

I am learning pointer and reference variables in C++, and there is a sample code I saw. I am not sure why the value of *c changed from 33 to 22. Could someone help me understand the process?

int a = 22;
int b = 33;
int* c = &a; //c is an int pointer pointing to the address of the variable 'a'
int& d = b; //d is a reference variable referring to the value of b, which is 33.
c = &b; //c, which is an int pointer and stored the address of 'a' now is assigned address of 'b'
std::cout << "*c=" << *c << ", d=" << d << std::endl; //*c= 33 d= 33
d = a; //d is a reference variable, so it cannot be reassigned ?
std::cout << "*c=" << *c << ", d=" << d << std::endl; //*c= 33 d= 33

Answer
d = a; //d is a reference variable, so it cannot be reassigned ?

That's a misunderstanding. That statement assigns the value of a (22) to the variable that d is a reference to (b). It does change what d is a reference to. Hence, after that line is executed, the value of b is 22.