Can we change the value of an object defined with const through pointers?

前端 未结 10 1328
北恋
北恋 2020-11-22 10:49
#include 
int main()
{
    const int a = 12;
    int *p;
    p = &a;
    *p = 70;
}

Will it work?

10条回答
  •  一个人的身影
    2020-11-22 11:10

    It's undefined behaviour. Proof:

    /* program.c */
    
    int main()
    {
            const int a = 12;
            int* p;
            p = &a;
            *p = 70;
            printf("%d\n", a);
            return 0;
    }
    
    
    gcc program.c
    

    and run it. Output will be 70 (gcc 4.3)

    Then compile it like this:

    gcc -O2 program.c
    

    and run it. The output will be 12. When it does optimisation, the compiler presumably loads 12 into a register and doesn't bother to load it again when it needs to access a for the printf because it "knows" that a can't change.

提交回复
热议问题