2

I am using const_cast to remove the constness of an integer.

#include<iostream>
int main(){
        const int pi = 3;
        int & pie = const_cast<int &>(pi);
        pie = 4;
        std::cout<<pi << " " << &pi << " " << pie << " " << &pie << std::endl;
};

Output:

root@ubuntu-OptiPlex-380:~/cpp# ./a.out
3 0x7fffdbc66f1c 4 0x7fffdbc66f1c

Can anyone kindly explain how the same memory location can hold different values?

santhosh
  • 111
  • 1
  • 3
  • 6
  • 3
    close dup of [How is a variable at the same address producing 2 different values?](http://stackoverflow.com/questions/22656734/how-is-a-variable-at-the-same-address-producing-2-different-values), basically it is undefined behavior. – Shafik Yaghmour May 23 '14 at 11:51
  • As to what is actually happening here: I guess the compiler replaces the `pi` evaluation by the actual constant 3, i.e. this line would be `std::cout << 3 << " " << &pi << " " << pie << " " << &pie << std::endl`. – filmor May 23 '14 at 11:55
  • Just found a more exact duplicate. – Shafik Yaghmour May 23 '14 at 12:01
  • That isn't how you use const_cast. it only works correctly if the **origin** of the const in question is, in fact, non-const. a *declared* const doesn't qualify. `int p=3; const int& pi = p;...` then the rest of your code would be worth a look. – WhozCraig May 23 '14 at 12:02

0 Answers0