Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 450
glen Avatar asked Jan 26 '26 06:01

glen


2 Answers

That is a compiler bug. The code should print 20 20.

like image 121
Puppy Avatar answered Jan 28 '26 01:01

Puppy


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).

like image 42
Nawaz Avatar answered Jan 28 '26 00:01

Nawaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!