0

As much as I know, const_cast may be used to cast away (remove) constness or volatility. But I could not understand the execution of the code below.

 #include <iostream>

 int main()
 {
     const int i = 20;
     int *p = const_cast<int*>(&i);
     std::cout << "i:" << i << "   *p:" << *p << "   p:" << p << "   &i:" << &i << std::endl;

     (*p)++;
     std::cout << "i:" << i << "   *p:" << *p << "   p:" << p << "   &i:" << &i << std::endl;
     return 0;
}

When I tried to run the above code, following result was obtained:

i:20   *p:20   p:0x7ffc579d18e4   &i:0x7ffc579d18e4
i:20   *p:21   p:0x7ffc579d18e4   &i:0x7ffc579d18e4

Can anyone explain me the output. I am new to C++ and trying to understand different casting operation. Thanks in advance

Sourav
  • 145
  • 1
  • 14
  • Do not be confused by the fact the cast in the dupe occurs in another function. It's exactly the same question save for that. – StoryTeller - Unslander Monica Mar 27 '18 at 14:14
  • 5
    Yes, `const_cast` can be used to remove `const` but if you violate the `const` contract and modify something that was declared `const` then you have undefined behavior. – NathanOliver Mar 27 '18 at 14:15
  • 1
    Using `const_cast` to remove `const` from something that was declared `const` and then access it in a non-const way is Undefined Behaviour. – Jesper Juhl Mar 27 '18 at 14:16
  • 1
    Just because you can do something, and the compiler does not complain, does *not* make it valid. – Jesper Juhl Mar 27 '18 at 14:17
  • Correction: _"`const_cast` may be used to cast away (**pretend to** remove) constness or volatility"_ – Lightness Races in Orbit Mar 27 '18 at 14:49
  • @JesperJuhlI am not talking about it's valid or not valid. All I want to know how is it even possible for the same memory location to show two different value. whats really happening over here? for example, when I pass a reference(which is a constant) to a thread, I know that variable is a reference to the temporary value copied at the new thread’s stack( it has a different memory location) but that's not the case here. – Sourav Mar 29 '18 at 10:15
  • @LightnessRacesinOrbit so if it just pretends to remove constness, then what is the purpose of having it? – Sourav Mar 29 '18 at 10:17
  • @Sourav: Not much. Some hacks when you are forced to deal with C APIs that "implement" `const` only by documentation. – Lightness Races in Orbit Mar 29 '18 at 10:25

0 Answers0