glen
glen

Reputation: 31

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.

Upvotes: 3

Views: 260

Answers (4)

Hiren
Hiren

Reputation: 77

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

Upvotes: 0

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361762

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

Upvotes: 4

Mahesh
Mahesh

Reputation: 34655

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.

Upvotes: 3

Puppy
Puppy

Reputation: 147036

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

Upvotes: 6

Related Questions