c语言改变const变量和static const变量的值

change the values of const variable and static const variable in c language

我有两个程序:

第一个节目:

#include<stdio.h>
int main()
{
    static const int a = 10;
    int * b;
    b = &a;
    *b = 200;
    printf("%d", a);

    return 0;
}

第二个节目:

#include<stdio.h>

int main()
{
    const int a = 10;
    int * b;
    b = &a;
    *b = 200;
    printf("%d", a);

    return 0;
}

第一个程序出现运行时错误:“总线错误:10”,但第二个程序运行良好。 你能告诉我这两个程序中const和static const有什么区别吗!

两个程序都执行语句 int *b; b = &a; *b = 200;,这会调用未定义的行为,因为 aconst int,因此不应修改。没有正确的答案(预期输出)——崩溃和不崩溃都是可以接受的结果,就像打印 10200(或 lemons and oranges——虽然这不太可能发生)。

不要执行任何会导致未定义行为的事情!

你的编译器应该在抱怨;注意它的警告。如果它没有抱怨,请获得更好的编译器。

区别在于static const int a = 10;变量被放置在一个只读段中(可能是文本段的一部分,虽然它真的无关紧要),所以系统可以在你写入它时发现并且导致崩溃。另一方面,const int a = 10; 放在堆栈上,堆栈是可修改的,所以不会崩溃。