Const variable changed with pointer in C(用 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
",*ip);
printf("%d
",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
推荐答案
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.
例如,如果我使用带有 -O2 优化级别的 gcc 编译您的示例代码,输出为:
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.
这篇关于用 C 中的指针更改常量变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用 C 中的指针更改常量变量
基础教程推荐
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
