Just re-assign a reference Variable? or have i? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Just re-assign a reference Variable? or have i?

Read in books..., watched videos about reverence variable and that you can't re-assign once assigned (it's a fixed connection) so...why does this compile o.k, (only relevant code show) int a = 10; int b = 20; int &c = a; cout << a << ' ' << c << endl; c = b; // <-- should not be able to do this; cout << b << ' ' << c << endl; Am i mis-understanding something?

2nd Sep 2019, 5:15 PM
rodwynnejones
rodwynnejones - avatar
2 Answers
+ 1
ahhhhh thank you...didn't think to check the value of 'a'.
2nd Sep 2019, 5:31 PM
rodwynnejones
rodwynnejones - avatar
+ 1
int &c = a means that c is now referencing the same memory area as a, what ever changes that are made in either c or a will reflect in both variables meaning they both refer to the same place in memory. c=b; here c is not referring to the memory area of b like it did with a, instead its just assigning the value of b so a and b and c will all equal 20 at this point; If you change the value of c and print b, the value of b will remain the same only c and a would of changed as they refer to the same place in memory.
2nd Sep 2019, 7:42 PM
D_Stark
D_Stark - avatar