You are trying to write on a variable (b
) which was declared const
. This is undefined behavior
in C++. Undefined behavior means, that the program may do anything at this point, everything is valid, including printing completely wrong numbers or even crashing.
You first promised that b
is constant and they you broke this promise.
The compiler gave you a hint that what you do is not allowed, by forcing you to insert a cast. Without the (int*)
cast your code will not compile, because it is not const correct. Casting around const
is often a hint that something is not correct. There are legitimate uses for casting around const
, but not in situations like your code where the underlying variable is really const
.
The cases where you are allowed to cast around const
all involve a non-const variable, and having a const pointer to it, and then casting the const
pointer to a non-const one, for example since you still maintain logical constness, e.g. you maintain an important invariant. But the underlying storage is always non-const in these scenarios.
This is most likely what happens in your scenario:
The compiler remembers that you want to give the value 5 the name b
. It also realizes that you are taking a pointer to b
, so in addition it reserves space for b
on the stack. It will most likely not even bother to put the 5 onto the stack until you try to read it, but you never do. Instead you overwrite the location for b
on the stack with 6. So the print statements first print a 6 (for the location of b on the stack) and then a 5 (the compiler simply inserts a 5 everywhere where you use b
).