在C中,函数内的static const
和const
之间有什么区别?
例如,采用给定的代码示例:
void print_int(int x) {
assert( x < 5 && x > -5 );
const int i[9] = {
-4, -3, -2, -1, 0, 1, 2, 3, 4
};
printf("%i", i[x + 4]);
}
int main() {
print_int( 1 );
return 0;
}
对战:
void print_int(int x) {
assert( x < 5 && x > -5 );
static const int i[9] = {
-4, -3, -2, -1, 0, 1, 2, 3, 4
};
printf("%i", i[x + 4]);
}
int main() {
print_int(1);
return 0;
}
如果我使用static const
代替const
,生成的程序集会更好地优化,还是两个示例的输出都相同?哦,这些例子假设所有优化都已关闭,因为编译器可以有效地优化两者以产生相同的输出。
答案 0 :(得分:3)
如果我使用
static
,生成的程序集会更好地优化吗?const
代替const
,或两者的输出相同 实例
不,汇编不会相同,至少假设x86 ABI和相应的ISA。 静态存储持续时间的对象在程序启动之前初始化。 自动存储持续时间的对象在堆栈帧中进行管理,即按功能实例化。如果编译器决定,它们也可以直接存储在CPU寄存器中。
这两个示例之间没有显着的性能差异,因为I / O printf()
函数最耗时。