How is “const” implemented?

前端 未结 5 501
灰色年华
灰色年华 2021-02-06 04:30

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 trac

相关标签:
5条回答
  • 2021-02-06 05:01

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

    0 讨论(0)
  • 2021-02-06 05:08

    The compiler knows that ci is const because you told it so with the line

    const int ci = get_foo();
    

    As you pass ci around to other functions or assign it to other variables, the compiler preserves that const-ness by preventing you from doing anything that could potentially change its value.

    For example, the following produces a compiler error.

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

    Because the compiler won't let you modify the value of ci.

    0 讨论(0)
  • 2021-02-06 05:10

    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.

    0 讨论(0)
  • 2021-02-06 05:12

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

    0 讨论(0)
  • 2021-02-06 05:25

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

    Note that you actually can change the value of a const via pointer casting, 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
    
    0 讨论(0)
提交回复
热议问题