Const variable changed with pointer in C

前端 未结 5 936
心在旅途
心在旅途 2020-12-02 02:40

The variable i is declared const but still I am able to change the value with a pointer to the memory location to it. How is it possible?

int ma         


        
5条回答
  •  萌比男神i
    2020-12-02 02:57

    The const is not a request to the compiler to make it impossible to change that variable. Rather, it is a promise to the compiler that you won't. If you break your promise, your program is allowed to do anything at all, including crash.

    For example, if I compile your example code using gcc with the -O2 optimisation level, the output is:

    100
    11
    

    The compiler is allowed to place a const qualified variable in read-only memory, but it doesn't have to (apart from anything else, some environments don't implement any such thing). In particular, it is almost always impractical for automatic ("local") variables to be placed in read-only memory.

    If you change the declaration of of i to:

    static const int i = 11;
    

    then you may well find that the program now crashes at runtime.

提交回复
热议问题