Const references - C++
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).
const reference means it cannot change the value of the refferant. However, referrant can change it's value which in turn affects the reference. I don't know why you are getting the output you shown.
It actually changes and see the output here.
Just to add one more point here, const
reference doesn't require lvalue to initialize it. For example
int &r = 10; //ERROR: lvalue required
const int &cr = 10; //OK
精彩评论