Title

Monday, 19 January 2015

Strange behavior of const_cast


Consider the following code:

I declare a new reference end assign it to value a via const_cast. Then I just increase the reference value print the addresses and values.

#include <iostream>  using namespace std;  int main()  {   const int a = 7;   int &b = const_cast<int&>(a);   ++b;   cout<<"Addresses "<<&a<<" "<<&b<<endl;   cout<<"Values "<<a<<" "<<b<<endl;  }    //output  Addresses 0x7fff11f8e30c 0x7fff11f8e30c  Values 7 8

How can i have 2 different values in the same address??

Answer

Because modifying a variable declared to be const is undefined behavior, literally anything can happen.

Answer2

Modifying a constant object gives undefined behaviour, so your program could (in principle) do anything.

One reason for leaving this behaviour undefined is to allow the optimisation of replacing a constant variable with its value (since you've stated that the value can never change). That's what is happening here: a is replaced with the value 7 at compile time, and so will keep that value whatever you try to do to it at run time.

No comments:

Post a Comment