How is “const” implemented?

前端 未结 5 502
灰色年华
灰色年华 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: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.

提交回复
热议问题