Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the result of the Reference Operator "&" on const variables?

I was asked how can a value of a const variable can be changed.

My my obvious answer was "pointers!" but I tried the next piece of code and I'm puzzled...

int main()
{
    const int x = 5;
    int *ptr = (int *)(&x); // "Cast away" the const-ness..
    cout << "Value at " << ptr << ":"<< (*ptr) <<endl;
    *ptr = 6;
    cout << "Now the value of "<< ptr << " is: " << (*ptr) <<endl;
    cout << "But the value of x is still " << x <<endl;
    return 0;
}

And the output was:

Value at <some address> :5
Now the value of <same address> is: 6
But the value of x is still 5

Now, I'm not sure exactly what is returned from '&x' but it's definitely not the actual address of x, since the value at x wasn't changed!

But on the over hand, ptr did contain the value of x at the beginning! So, what is it exactly?

EDIT compiled with VS2010

like image 829
Avi Shukron Avatar asked Nov 13 '11 22:11

Avi Shukron


1 Answers

Your program invokes undefined behavior (writing to a const variable through a pointer is undefined behavior), so anything might happen. That being said here's the most likely explanation why you get the behavior you see on your particular implementation:

When you do &x, you do get the address of x. When you do *ptr = 6, you do write 6 to x's memory location. However when you do cout << x, you don't actually read from x's memory location because your compiler optimized the code by replacing x with 5 here. Since x is const the compiler is allowed to do that since there is no legal C++ program in which doing so would change the program's behavior.

like image 153
sepp2k Avatar answered Oct 07 '22 13:10

sepp2k