Const变量随C中的指针而改变 [英] Const variable changed with pointer in C

查看:89
本文介绍了Const变量随C中的指针而改变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

变量 i 声明为const,但我仍然可以使用指向内存位置的指针来更改该值。如何可能?

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 main()
{

    const int i = 11;
    int *ip = &i;
    *ip=100;
    printf("%d\n",*ip);
    printf("%d\n",i);
}



当编译时,我收到此警告:

When I compile, I get this warning :

test.c: In function ‘main’:
test.c:11: warning: initialization discards qualifiers from pointer target type

输出为

100
100


推荐答案

c $ c> const 不是对编译器的请求,使其不可能更改该变量。相反,这是一个对编译器的承诺,你不会。

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.

例如,如果我使用gcc编译你的示例代码,使用 -O2 优化级别,输出为:

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

100
11

编译器允许放置 const 限定变量在只读存储器中,但它不(除了别的,一些环境不实现任何这样的事情)。具体来说,将自动(本地)变量放置在只读存储器中几乎总是不切实际的。

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.

如果更改 i 到:

static const int i = 11;

那么你可能会发现程序现在运行时崩溃。

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

这篇关于Const变量随C中的指针而改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆