Modifying a const through a non-const pointer

Posted by jasonline on Stack Overflow See other posts from Stack Overflow or by jasonline
Published on 2010-03-24T14:46:05Z Indexed on 2010/03/24 14:53 UTC
Read the original article Hit count: 422

Filed under:
|
|
|
|

I'm a bit confused what happened in the following code:


const int e = 2;

int* w = ( int* ) &e;          // (1) cast to remove const-ness
*w = 5;                        // (2)

cout << *w << endl;            // (3) outputs 5
cout << e << endl;             // (4) outputs 2

cout << "w = " << w << endl;   // (5) w points to the address of e
cout << "&e = " << &e << endl;

In (1), w points to the address of e. In (2), that value was changed to 5. However, when the values of *w and e were displayed, their values are different. But if you print value of w pointer and &e, they have the same value/address.

How come e still contained 2, even if it was changed to 5? Were they stored in a separate location? Or a temporary? But how come the value pointed by w is still the address of e?

© Stack Overflow or respective owner

Related posts about c++

Related posts about const