Weird behavior when using pointers [migrated]
- by Kinan Al Sarmini
When I run this code on MS VS C++ 2010:
#include <iostream>
int main() {
const int a = 10;
const int *b = &a;
int *c = (int *)b;
*c = 10000;
std::cout << c << " " << &a << std::endl;
std::cout << *c << " " << a << " " << *(&a) << std::endl;
return 0;
}
The output is:
0037F784 0037F784
10000 10 10
The motivation for writing that code was this sentence from "The C++ Programming Language" by Stroustrup:
"It is possible to explicitly remove the restrictions on a pointer to const by explicit type conversion".
I know that trying to modify a constant is conceptually wrong, but I find this result quite weird. Can anyone explain the reason behind it?