You are asking why you can assign values to const variables, but they don't show up when queried. And why it does not "work" on global scope.
Well, actually it does not work on either scope - global or local. What you do is "undefined behaviour" and this means that the programm can do what it wants, including crashing and doing weird things like ignoring your variables.
The problem is, that the variable was declared const in the first place, so you got a real and true const variable. And for that, you are just not allowed to change its value, period. ;)
You can use const_cast (or any normal old-style C-cast) to remove the const specifyer to trick your compiler into believing it is a non-const variable, but you are still not allowed to change the memory behind the variable. The compiler gets this as guarantee from the C++ standard and usually use this guarantee to optimize code.
For example, the compiler may put the memory location of the variable into some read-only data segment (or even in the code segment). The operating system will then enforce, that nothing writes on these memory pages and rather kill the process by a segfault then allowing the write operation.
As you have already seen, the compiler even can remove the variable completely from the binary (except if you attempt to get its address - in this case the compiler generates some dummy place. But still he can give you any address, including pointers to some read-only memory pages.)
Here an example where you can use const_cast and where not:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
int m = 0; // not declared const!
const int mconst = 1;
int main()
{
const int* p = &m; // const pointer to a non-const variable
int* i = const_cast<int*>(p); // remove the const again.
*i = 42; // writing to the variable. This is ONLY possible, if m was never declared const in the first place
// possible, as long as you never ever write to the location i2 is pointing to
int* i2 = const_cast<int*>(&mconst);
// *i2 = 23; <-- don't do this! You are not allowed to write to const-memory locations.
}
|