How is const implemented?

How does the compiler, C or C ++ (e.g. gcc) honor the const declaration?

For example, in the following code, how does the compiler track that ci is equal to const and cannot be changed?

 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? } 
+7
source share
5 answers

Like any other bit of symbolic information for variables (address, type, etc.). Usually there is a symbol table that stores information about the declared identifiers, and this is done each time the identifier is accessed.

(A more interesting question is whether this knowledge is present only at compile time or even at run time. Most languages ​​discard the symbol table after compilation, so you can manipulate the compiled code and force a new value, even if the identifier has been declared 'const' To prevent this, a complex runtime system (and code signing) is required.

+9
source

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

+3
source

The compiler knows that ci is const because you said it this way with the line

 const int ci = get_foo(); 

When you pass ci around to other functions or assign it to other variables, the compiler saves this constant, preventing you from doing anything that could potentially change its value.

For example, the following leads to a compiler error.

 int *ci2 = &ci; (*ci2)++; 

Since the compiler will not allow you to change the value of ci.

+1
source

I'm sure others can develop more, but in short, yes. The compiler keeps track of all type specifiers, so that it knows that ci is of type "const int", not "int".

+1
source

As others have said, const tracked by the compiler in the same way that the compiler tracks the fact that the variable is int . In fact, I read that at least gcc considers const int different type from int , so it is not even tracked as a modifier, it tracks the same as int .

Note that you can actually change the value of const using a pointer cast, but the result is undefined:

 #include <stdio.h> #include <stdlib.h> int main(void) { const int c = 0; printf("%d\n", c); ++*(int*)&c; printf("%d\n", c); } 

On my machine using gcc this prints

 0 1 

But compiling with g ++ gives

 0 0 
+1
source

All Articles