C++ – Understanding the Implementation of ‘const’

c++constants

How does a compiler, C or C++, (for example, gcc) honors the const declaration?

For example, in the following code, how does the compiler keeps track that the variable ci is const and cannot be modified?

int
get_foo() {
    return 42;
}

void
test()
{
    int i = get_foo();
    i += 5;

    const int ci = get_foo();
    // ci += 7;  // compile error: assignment of read-only variable ?ci?
}

Best Answer

Much like any other bit of symbol information for variables (address, type etc.). Usually there is a symbol table which stores information about declared identifiers, and this is consulted whenever it encounters another reference to the identifier.

(A more interesting question is whether this knowledge is only present during compilation or even during runtime. Most languages discard the symbol table after compiling, so you can manipulate the compiled code and force a new value even if the identifier was declared 'const'. It takes a sophisticated runtime system (and code signing) to prevent that.)