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?
}
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With