问题描述
是
int main()
{
int a;
int b = (a = 0, a) + (a = 1, a);
}
定义了吗?在每个术语中都没有,a
的情况下,由于对 a
的多次无顺序写入,程序行为显然是不确定的,但请不要引入,
足够的测序点?
defined? Without the , a
in each term, the program behaviour is clearly undefined due to multiple unsequenced writes to a
, but don't the ,
introduce adequate sequencing points?
推荐答案
否,它定义不明确.假设我们用伪代码"SQ"替换您代码中的所有序列点:
No it isn't well-defined. Suppose we replace all sequence point in your code with pseudo code "SQ":
SQ
int b = (a = 0 SQ a) + (a = 1 SQ a) SQ
然后我们有 SQ a)+(a = 1 SQ
,其中两个访问和一个副作用发生在序列点之间的 a
上,所以它仍然是未定义的行为.
Then we have SQ a) + (a = 1 SQ
where two accesses and one side effect happens to a
between sequence points, so it is still undefined behavior.
我们可以编写定义良好(但当然非常糟糕和可疑)的代码,如下所示:
We could write well-defined (but of course very bad and fishy) code like this:
(0, a = 0) + (0, a = 1)
仍未指定+操作数的求值顺序,但是编译器必须在对下一个括号进行求值后才能继续进行下一个运算.因此,在 a
的副作用/访问之间始终有一个逗号运算符序列点.
The order of evaluation of the + operands is still unspecified, but the compiler must evaluate either parenthesis before moving on to the next. So there's always a comma operator sequence point between the side-effects/access of a
.
这篇关于(a = 0,a)+(a = 1,a)是int a的不确定行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!