简体   繁体   English

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

[英]Is the behavior of the following C program undefined?

I'm looking in one of my old courses and I find the following: 我正在查看我的一门旧课程,发现以下内容:

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

"According to C standard, the behavior of the program above is undefined. “根据C标准,上述程序的行为是不确定的。

GCC4, MSVC: returns 4 GCC4,MSVC:返回4

GCC3, ICC, Clang: returns 3" GCC3,ICC,C语:返回3英寸

There's a slide after this saying the following code is not undefined in the C standard. 这之后有一张幻灯片,说下面的代码在C标准中不是未定义的。 Can anyone explain to me why it's not undefined behavior? 谁能向我解释为什么它不是未定义的行为?

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

Relevant passages from the C specification: 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. 给定A和B的任何两个值,如果A在B之前排序,则A的执行应在B的执行之前。(相反,如果A在B之前的排序,则B在A之后的排序。) 如果A没有排序在B之前或之后,则A和B是无序列的。

and

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. 如果一个表达式的子表达式有多个允许的排序,则如果在任何排序中都出现这种无序的副作用,则行为是不确定的。


Thus, both snippets in your question invoke undefined behavior. 因此,问题中的两个代码片段均会调用未定义的行为。

(Because originally your second snippet was C++, it's worth mentioning that even though recent versions of C++ have expanded the notion of what "sequenced before" and "sequenced after" mean, AFAIK it still doesn't include operator+ as a sequence point.) (由于最初的第二个片段是C ++,所以值得一提的是,即使最新版本的C ++扩展了“先序列化”和“后序列化”的含义,但AFAIK仍然没有将operator+作为序列点。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM