问题描述
根据讨论,我想知道函数作用域是否静态变量总是使用内存或者允许编译器优化。为了说明这个问题,假设一个类似这样的函数:
Based on this discussion, I was wondering if a function scope static variable always uses memory or if the compiler is allowed to optimize that away. To illustrate the question, assume a function like such:
void f() {
static const int i = 3;
int j = i + 1;
printf("%d", j);
}
编译器很可能内联 i
,并且可能在编译时执行计算 3 + 1
。由于这是唯一使用 i
的值,因此不需要分配任何静态内存。因此,编译器允许优化静态变量,或者标准的任何静态变量都分配了内存。
The compiler will very likely inline the value of i
and probably do the calculation 3 + 1
at compile time, too. Since this is the only place the value of i
is used, there is no need for any static memory being allocated. So is the compiler allowed to optimize the static away, or does the standard mandate that any static variable has memory allocated?
推荐答案
根据标准:
...和脚注说:
这意味着只要可观察的行为是相同的,编译器就可以做任何它想要的代码。因为你没有接受 static const
的地址,编译器可以将值优化为一个恒定积分表达式。
What this all means is that the compiler can do anything it wants to your code so long as the observable behavior is the same. Since you haven't take the address of the static const
, the compiler can optimize the value away to a Constant Integral Expression.
这篇关于静态变量总是占用内存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!