Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is "const" implemented?

Tags:

c++

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?
}
like image 527
Arun Avatar asked Oct 25 '11 17:10

Arun


2 Answers

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.)

like image 200
Kilian Foth Avatar answered Oct 06 '22 13:10

Kilian Foth


Of course it is up the implementation of each compiler, but in a nutshell, it stores the variable's const and volatile qualifiers (if any) in its variable symbol table along with other information such as the variable's type and whether or not it is a pointer / reference.

like image 35
Michael Goldshteyn Avatar answered Oct 06 '22 13:10

Michael Goldshteyn