常量变量用 C 中的指针改变

Const variable changed with pointer in C(常量变量用 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 中的指针改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)