简体   繁体   中英

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 ie 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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM