1

Here is the test code:

int main()
{
    const int a = 10;
    int * b = const_cast<int *>(&a);
    *b = 3;
    printf("%x %x %d %d",&a,b,a,*b);
}

it print

22ff18 22ff18 10 3

I want to know why *b and a print different answer? it share the same address!

maple
  • 1,828
  • 2
  • 19
  • 28
  • 4
    This is [undefined behavior to attempt to modify a const variable](http://stackoverflow.com/questions/22656734/how-is-a-variable-at-the-same-address-producing-2-different-values) – Shafik Yaghmour Aug 27 '14 at 14:10
  • Undefined Behaviour. There is no way to reason about it without reference to the underling implementation. There is also very little reason to ever have it in your program. Don't cast away const. – Mankarse Aug 27 '14 at 14:10
  • 1
    @Mankarse Then, When should we use const_cast? – maple Aug 27 '14 at 14:14
  • @FredLarson it is not an exact duplicate and after [I was scolded a little while ago](http://meta.stackoverflow.com/questions/266364/why-was-my-question-marked-duplicate-citing-an-existing-similar-answer) I have been more cautious with this. – Shafik Yaghmour Aug 27 '14 at 14:14
  • @maple `const_cast` is valid if the object you're pointing to isn't `const`. For instance, `int a = 0; const int* b = &a; int* c = const_cast(b); *c = 2;` is valid, because `a` isn't `const`. – molbdnilo Aug 27 '14 at 14:21
  • @maple [When const_cast can be used](http://stackoverflow.com/q/357600/3821804); [possible explanation of what you saw here.](http://stackoverflow.com/a/4518788/3821804) – GingerPlusPlus Aug 27 '14 at 14:22
  • [Possible duplicate](http://stackoverflow.com/q/4518630/3821804) – GingerPlusPlus Aug 27 '14 at 14:23

0 Answers0