How is “const” implemented?

前端 未结 5 500
灰色年华
灰色年华 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: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 
    #include 
    
    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
    

提交回复
热议问题