gpt4 book ai didi

c++ - 不稳定和双重困惑

转载 作者:可可西里 更新时间:2023-11-01 18:37:20 25 4
gpt4 key购买 nike

int x = 2;
volatile int y = 2;

const int z = x/y;

int main(){
int x = 2 + 3;

double d = 7 / 3;
}

我这里有三个问题:

首先,在这种情况下,编译器能否在编译时将'z'的值计算为1?

其次,我观察到编译器不会生成将 2 和 3 相加来初始化 x 的汇编指令。它直接用 5 初始化 x。可以用 'd' 做同样的事情吗?

第三,这两个概念有什么好书可以读吗?任何来自标准的引用都会有所帮助(标准文档似乎是一个有趣的地方,虽然很可怕)

最佳答案

Firstly, can the compiler calculate the value of the 'z' at compile time to be 1 in this case?

没有。读取或写入被认为具有副作用的 volatile 变量,因此不允许编译器执行此操作。

Secondly, I observed that the compiler does not generate assembly instructions for adding 2 and 3 to initialize x. It directly initializes x with 5. Can the same be done with 'd'?

是的。只要编译器能证明没有副作用就可以了。例如。如果在计算过程中发生溢出或被零除,则无法在编译时计算它,因为计算应该在运行时触发 CPU 异常。

Thirdly, Is there any good book to read on these two concepts?

是的。 C++ ISO 标准准确描述了您的要求。书籍很适合学习基础知识或理论。编写重新表述标准中描述的所有技术细节的书籍是没有意义的。

关于c++ - 不稳定和双重困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3845883/

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