ZeroSevenTen
ZeroSevenTen

Reputation: 1394

Does a const variable store the value in the variable?

I was messing around in C++ and wrote this code

#include <iostream>

int main() {
    const int x = 10;
    const int* ptr = &x;

    *((int*)ptr) = 11;

    std::cout << "ptr -> " << ptr << " -> " << *((int*)ptr) << std::endl;
    std::cout << "x ->   " << &x << " -> " << x << std::endl;
}

Interestingly, the output in the console is:

ptr -> 00CFF77C -> 11
x ->   00CFF77C -> 10

I checked the value at the memory address of ptr and the value is 11, so does this imply that const variables store the value in them, and not in memory? And if this were the case, why have a memory address storing the value?

Upvotes: 3

Views: 96

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 595782

Your code has Undefined Behavior.

x is a compile time constant, so the compiler expects it to not change value at runtime. As such, the compiler is allowed to optimize code by substituting uses of x's value with the literal value 10 at compile time.

So, at the point where << x is used, your compiler is emitting code for << 10 instead.

But, since your code is also using &x, the compiler is required to make sure that x has a memory address accessible at runtime. That means allocating a physical int and initializing its value to 10. Which you are then fiddling with in an unsafe manner, despite the fact that most compilers will likely place that int in read-only memory.

That is why you are seeing the output you see. But you are lucky your code is not crashing outright, trying to assign a new value to a constant at runtime.

Upvotes: 7

Miles Budnek
Miles Budnek

Reputation: 30494

The behavior of a program that writes to a const variable is undefined. It could print "10", it could print "11", it could print "3822", it could crash, or it could make demons fly out of your nose.


That said, in this case the behavior makes perfect sense. The compiler knows x is never allowed to change, so it transforms your std::cout << x to basically std::cout << 10.

Upvotes: 5

Related Questions