gpt4 book ai didi

c - 在函数内使用 const 和 static const 的速度有区别吗?

转载 作者:行者123 更新时间:2023-12-02 14:24:06 25 4
gpt4 key购买 nike

在 C 语言中,static constconst 在函数内部有什么区别?

例如,采用给定的代码示例:

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,生成的程序集是否会得到更好的优化,或者两个示例的输出是否相同?哦,这些示例假设所有优化都已关闭,因为编译器可以有效地优化两者以产生相同的输出。

最佳答案

Would the generated assembly be optimized better if I used static const instead of const, or would the output be the same for both examples?

不,程序集不会相同,至少假设 x86 ABI以及相应的ISA。 静态存储持续时间的对象在程序启动之前被初始化。 自动存储持续时间的对象在堆栈帧内管理,即按函数实例化。如果编译器决定的话,它们也可以直接存储在 CPU 寄存器中。

这两个示例之间不会有显着的性能差异,因为 I/O printf() 函数最耗时。

关于c - 在函数内使用 const 和 static const 的速度有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31813134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com