基于
this的讨论,我想知道函数作用域静态变量是否总是使用内存,或者是否允许编译器对其进行优化.为了说明这个问题,假设一个这样的函数:
void f() {
static const int i = 3;
int j = i + 1;
printf("%d",j);
}
编译器很可能内联i的值,并且可能在编译时进行计算3 1.由于这是使用i值的唯一位置,因此不需要分配任何静态内存.那么编译器是允许优化静态的,还是标准要求任何静态变量都分配了内存?
解决方法
So is the compiler allowed to optimize the static away[…] ?
是.根据标准:
1.9程序执行
The semantic descriptions in this International Standard define a parameterized nondeterministic abstract machine. This International Standard places no requirement on the structure of conforming implementations. In particular,they need not copy or emulate the structure of the abstract machine. Rather,conforming implementations are required to emulate (only) the observable behavior of the abstract machine as explained below.5)
……脚注说:
5) This provision is sometimes called the “as-if” rule,because an implementation is free to disregard any requirement of this International Standard as long as the result is as if the requirement had been obeyed,as far as can be determined from the observable behavior of the program. For instance,an actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no side effects affecting the observable behavior of the program are produced.
这一切意味着只要可观察行为相同,编译器就可以对代码执行任何操作.由于您没有获取静态const的地址,因此编译器可以将值优化为常量积分表达式.
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|