1

Possible Duplicate:
const_casting question

The following code tries to change the value of const int a; but it seems a and b both point to same memory address but print out different values. Can somebody explain why?

const int a = 5;
int *b = const_cast<int*>(&a);
*b = 7; //not working why??
cout<<"\nConst Cast: "<<a<<"  "<<&a;
cout<<"\nConst Cast: "<<*b<<"  "<<b;
cout<<"\nConst Cast: "<<a<<"  "<<&a;

/* Output
Const Cast: 5  0027F7FC
Const Cast: 7  0027F7FC
Const Cast: 5  0027F7FC
*/
Community
  • 1
  • 1
  • 7
    You've told the compiler you promise not to modify the value of `a`, then you go break that promise two lines later and modify it. That's invoking undefined behavior, which for all intents and purposes means "**DON'T DO IT**". – In silico Mar 08 '12 at 02:11
  • when you did `const int a=4;` you assign `a` with a constant expression which can be evaluated at compile time, so that's why your compiler replace wherever it saw `a` with it's value. so the value of `a` changed indeed. if you tried to set `a` with a non-const expression then you will get the result you would have expected. – AlexDan Jan 07 '13 at 00:32

2 Answers2

5

const_cast is not there to allow you to modify a constant object, but rather to drop the const-ness of a reference/pointer to a non-const object and to be able to call old broken interfaces where the library would not modify, but took a non-const pointer. Modifying an object tha is const is undefined behavior.

Now on the practical test you have. Chances are that the compiler has substituted the value of compile time constant a (which you promised that was 5) into the different uses in the function. When you print a the compiler is printing 5, not reading the value.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
4

You lied to the compiler. You told it that a was const, so it went ahead and treated it as if it was so, replacing instances of a with the compile time constant 5.

What you're doing is undefined behavior.

Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274