const and casting

Okay, for an intellectual exercise, I was digging in to the C++ spec. I was attempting to see how modifying a value stored in a const worked with my compiler.

I know, this should never be done. But I wanted to see what my compiler did in such a situation. The results confounded me.

I'm using Cygwin and the g++ compiler to compile the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void changeConst() {
	const int i = 1;
	int* ptr = (int*)&i; // ptr thinks it is pointing to an int, not a const int
	
	std::cout << "Value of i: " << i << "\r\n"; // 1
	std::cout << "Address of i: " << &i << "\r\n"; // 0x28cd14
	std::cout << "Value of ptr: " << ptr << "\r\n"; // 0x28cd14
	std::cout << "Value stored in ptr: " << *ptr << "\r\n"; // 1
	*ptr = 2;
	std::cout << "New value of ptr: " << ptr << "\r\n"; // 0x28cd14
	std::cout << "Value stored in ptr: " << *ptr << "\r\n"; // 2
	std::cout << "Value of i: " << i << "\r\n"; // 1
	std::cout << "Address of i: " << &i << "\r\n"; // 0x28cd14
}


So according to the output, ptr is pointing to the original i, and outputs a "2" when the value of i is "1".

The output looks like one memory address is storing two different values. That of course cannot be the case. So the question I'm asking is what is going on here? I'm guessing that compiler optimization is hiding what the true values are. But perhaps I am naive to another issue that is at play.

Additional information: I stepped through the code using VS 2010, and saw the value of i change to 2, while the console output still displayed 1. So I'm thinking the compiler optimized line 12.

Your thoughts?
Last edited on
The compiler must have exchanged your references of constant i with its corresponding value.
Topic archived. No new replies allowed.