I had a doubt regarding the concept of const references in C++.
int i =10;
const int &j = i;
cout<<"i="<<i<<" j:"<<j; // prints i:10 j:10
i = 20;
cout<<"i="<<i<<" j:"<<j; // prints i:20 j:10
Why second j statement doesn't print the new value i.e 20.
How it is possible if references to any variable denotes strong bonding between both of them.
That is a compiler bug. The code should print 20 20.
I don't see any reason why j wouldn't print 20 in the second cout.
I ran this code :
int main() {
int i =10;
const int &j = i;
cout<<"i="<<i<<" j:"<<j << endl; // prints i:10 j:10
i = 20;
cout<<"i="<<i<<" j:"<<j << endl; // prints i:20 j:10
return 0;
}
And it gave me this output:
i=10 j:10
i=20 j:20
See the online demo yourself : http://ideone.com/ELbNa
That means, either the compiler you're working with has bug (which is less likely the case, for its the most basic thing in C++), or you've not seen the output correctly (which is most likely the case).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With