gpt4 book ai didi

c - 以下 C 程序的行为是否未定义?

转载 作者:太空宇宙 更新时间:2023-11-04 01:18:06 25 4
gpt4 key购买 nike

我正在查看我的一门旧类(class),发现以下内容:

int main(void) {
int x = 0;
return (x = 1) + (x = 2);
}

“根据 C 标准,上述程序的行为是未定义的。”

GCC4、MSVC:返回 4

GCC3、ICC、Clang:返回 3"

在此之后有一张幻灯片说以下代码在 C 标准中不是未定义的。谁能向我解释为什么这不是未定义的行为?

int main(void) {
int x = 0;
int y = 2;
return (x = 4) + (x=(x + y)/2);
}

最佳答案

C规范中的相关段落:

Given any two evaluations A and B, if A is sequenced before B, then the execution of A shall precede the execution of B. (Conversely, if A is sequenced before B, then B is sequenced after A.) If A is not sequenced before or after B, then A and B are unsequenced.

If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined. If there are multiple allowable orderings of the subexpressions of an expression, the behavior is undefined if such an unsequenced side effect occurs in any of the orderings.


因此,您问题中的两个片段都会调用未定义的行为。

(因为最初您的第二个代码段是 C++,值得一提的是,即使最新版本的 C++ 扩展了“前序”和“后序”的概念,据我所知,它仍然不包括 operator+ 作为序列点。)

关于c - 以下 C 程序的行为是否未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52123271/

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