为(x ++,y)+(Y +,X)未定义或不确定的,如果没有指定,那是什么计算? [英] Is (x++, y) + (y++, x) undefined or unspecified, and if unspecified, what can it compute?
问题描述
借助逗号序列算引入的顺序点在离pression 。我想知道这是否意味着,下面的程序避免不确定的行为。
The comma sequence operator introduces a sequence point in an expression. I am wondering whether this means that the program below avoids undefined behavior.
int x, y;
int main()
{
return (x++, y) + (y++, x);
}
如果它确实避免不确定的行为,它可能仍然是不确定的,也就是说,返回几个可能的值之一。我认为,在C99,它只能计算 1
,但实际上,GCC的各种版本编译这个程序进入返回可执行 2
。锵生成返回一个可执行 1
,显然与我的直觉同意。
If it does avoid undefined behavior, it could still be unspecified, that is, return one of several possible values. I would think that in C99, it can only compute 1
, but actually, various versions of GCC compile this program into an executable that returns 2
. Clang generates an executable that returns 1
, apparently agreeing with my intuition.
最后,就是这个东西,在C11改变?
Lastly, is this something that changed in C11?
推荐答案
就拿前pression:
Take the expression:
(x++, y) + (y++, x)
评估左到右:
x++ // yield 0, schedule increment of x
, // sequence point: x definitely incremented now
y // yield 0
y++ // yield 0, schedule increment of y
// explode because you just read from y and wrote to y
// with no intervening sequence point
有什么在禁止这一点,所以整个事情是未定义行为的标准。
There's nothing in the standard that forbids this, so the whole thing has undefined behavior.
对比度这个伪code:
Contrast this pseudocode:
f() { return x++, y; }
g() { return y++, x; }
f() + g()
Acoording到C99(5.1.2.3/2)的F的调用
和先按g
自己算的副作用和函数调用运算符包含它进入函数之前序列点。这意味着功能的执行不能交错。
Acoording to C99 (5.1.2.3/2) the calls to f
and g
themselves count as side effects, and the function call operator contains a sequence point just before it enters a function. This means function executions can't interleave.
在评价并行的东西的模式:
Under the "evaluate things in parallel" model:
f() // arbitrarily start with f: sequence point; enter f
g() // at the same time, start calling g: sequence point
由于 F的
执行算作一个副作用本身,在克序列点()
暂停执行直到˚F
又回来了。因此,没有未定义的行为。
Since the execution of f
counts as a side effect itself, the sequence point in g()
suspends execution until f
has returned. Thus, no undefined behavior.
这篇关于为(x ++,y)+(Y +,X)未定义或不确定的,如果没有指定,那是什么计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!