gpt4 book ai didi

C++:编译时的 int 计算(不是运行时)

转载 作者:行者123 更新时间:2023-12-03 06:51:48 24 4
gpt4 key购买 nike

简单的问题:
为什么下面的代码有效?

int main() {
const int a = 4;
const int b = 16;
const int size = b/a;
int arr[size] = {0,1,2,3};
return 0;
}
我认为静态数组的大小必须在编译时定义,因此只能使用“int”文字。在上面的代码中,尽管大小是一个计算,但代码可以编译。这个计算是在编译时完成的吗?
如果是的话,也许我对编译和运行的理解是错误的:编译只是通过语法并将代码转换为机器代码,但不做任何计算......
谢谢!

最佳答案

Is this calculation done during compile time?


,编译器为你做了很多优化和计算,你代码中的初始化没有任何优化也可以,这是编译器预先计算的结果。
一般来说,这里的计算包括 constexpr , const类型声明等,这些已经在语言本身的定义中(见 constant expression)。
compile-time const and example

just see the output of the example.


compile-time constexpr and example

The constexpr specifier declares that it is possible to evaluate the value of the function or variable at compile time.



This is how array can be initialized ,数组声明如下:

noptr-declarator [ expr(optional) ] attr(optional)


在这里, expr是:

an integral constant expression (until C++14) a converted constant expression of type std::size_t (since C++14), which evaluates to a value greater than zero


都是 constant expression ,其中说:

an expression that can be evaluated at compile time.


所以,使用所谓的预计算来初始化一个数组是可以的。
这里还有一个后续:还有很多方法可以通过让它们在编译时完成来节省更多计算和时间,它们显示在上面的链接中。

顺便提一下不同之处:至于优化,您可以看到版本 -O0 的汇编代码之间的差异。和 -O3计算时 从 1 到 100 的总和 ,这是一个令人震惊的 - 你会看到结果 5050 在 -O3 的汇编代码中版本 ,它也是一种编译时计算,但并非针对所有情况启用。

关于C++:编译时的 int 计算(不是运行时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63900087/

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