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
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.
Let's run this piece of code step by step:
int a = 22;
int b = 33;
We assigned values to a, b. Not much to say.
int* c = &a;
c holds the address of a. *c is the value of a, which is 22 now.
int& d = b;
d is a reference variable to b. From now on, d is treated as an alias of b. The value of d is also the value of b, which is 33.
c = &b;
c now holds the address of b. *c is the value of b, which is 33 now.
d = a;
We assigned 22 (value of a) to d. Since d is an alias of b, b is now also 22. And because c points to b, *c is the value of b, which is now 22.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.