本文介绍了gcc -O2标志影响,同时修改const int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

下面是示例应用程序test.c

  #include  
#include< stdlib.h>
$ b $ int main(int ac,char * av [])
{
const int i = 888;
printf(我是%d \\\
,i);
int * iPtr =& i;
* iPtr = 100;
printf(我是%d \\\
,i);
返回0;
}

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

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

这个好奇心让我写这个问题。

解决方案

修改声明为常量。未定义的行为是...未定义;换句话说,编译器可以做任何事情,包括,假设未定义的行为实际上没有发生。



在这种情况下,编译器可以优化通过假定它永远不会被改变来访问 const int i ;它允许编译器在 printf 调用中插入已知的初始值 i 。事实上,它可以预先计算在编译时输出的字符串,因为它知道 printf 应该做什么。



你可以通过指针绕过 const 声明并不是真的。如果变量最初被声明为 const ,则尝试修改它是无效的。你可以做的是创建一个 const 指向一个可变变量的指针,然后稍后绕过 const 指针通过将它扔掉。由于原始变量不是 const ,这是合法的(尽管通常不是一个好主意。)



标准参考:§ 6.7.3 / 6:如果尝试通过使用非const限定类型的左值修改用const限定类型定义的对象,则行为未定义。)


I know in C we can modify the 'const int' via pointer. But while compiling the program I enabled the '-O2' flag in gcc, and const int can't modify the value, so just wanted to know how gcc optimization flag affect the modifying 'const int'.

Here is the sample application 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

This curiosity leads me to write this question.

解决方案

It's undefined behaviour to modify a variable declared as const. Undefined behaviour is... undefined; in other words, the compiler can do anything including assuming that the undefined behaviour does not actually happen.

In this case, the compiler can optimize the access to const int i by assuming that it is never changed; that allows the compiler to insert the known initial value of i in the call to printf. In fact, it could precompute the string to be output at compile time, since it knows what printf is supposed to do.

It's not true that you can by-pass const declarations through pointers. If a variable is originally declared as const, attempts to modify it are not valid. What you can do is create a const pointer to a mutable variable, and then later get around the constness of the pointer by casting it away. Since the original variable is not const, that is legal (although not usually a good idea.)

(Obligatory standard reference: §6.7.3/6: "If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.")

这篇关于gcc -O2标志影响,同时修改const int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 01:03