c - gcc -O2 标志在修改 const int 时影响

标签 c gcc

我知道在 C 中我们可以通过指针修改“const int”。但是在编译程序时我在 gcc 中启用了 '-O2' 标志,并且 const int 不能修改该值,所以只是想知道 gcc 优化标志如何影响修改 'const int'。

这里是示例应用程序test.c

#include <stdio.h>
#include <stdlib.h>

int main(int ac, char *av[])
{
        const int i = 888;
        printf("i is %d \n", i);
        int *iPtr = &i;
        *iPtr = 100;
        printf("i is %d \n", i);
        return 0;
}

gcc -Wall -g -o test test.c
./test
i is 888 
i is 100

gcc -Wall -g -O2 -o test test.c
i is 888 
i is 888

这种好奇心促使我写下这个问题。

最佳答案

I know in C we can modify the 'const int' via pointer.

不,那是错误的。 C 语言标准明确指出修改const 对象是“未定义的行为”。这意味着任何事情都可能发生——代码可能成功,它可能崩溃,它可能损坏你的硬盘,或者让恶魔从你的 Nose 里飞出来。所有这些行为都被认为是合法的。因此,行为根据编译器的优化级别而改变这一事实也是完全合法的。

任何称职的编译器都会就此警告您。使用默认编译器选项,当我尝试编译代码时,GCC 会很有帮助地告诉我:

$ gcc test.c
test.c: In function 'main':
test.c:8:21: warning: initialization discards 'const' qualifier from pointer target type [enabled by default]

Clang 类似:

$ clang test.c
test.c:8:14: warning: initializing 'int *' with an expression of type
      'const int *' discards qualifiers
      [-Wincompatible-pointer-types-discards-qualifiers]
        int *iPtr = &i;
             ^      ~~

关于c - gcc -O2 标志在修改 const int 时影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21520282/

相关文章:

c - dos 基本系统中指针的大小

C语言定义这个变量的意思

c - 为什么不使用 GCC 构造函数/析构函数?

linux - 将 VC++ SetWaitableTimer 移植到 gcc

python - 使用 Python 的 CFFI 并排除系统头文件

c++ - 混合单独编译的对象

macos - OSX 如何使用位于当前工作目录或子目录 C/C++ 中的 GCC/G++ 编译框架

C:捕获空输入并打印命令提示符

c - 显示 RAND 字符的 ASCII 值

c - 为什么在初始化函数指针数组时有一个 "warning"?