我想我在某处看到了用逗号分隔的多于 1 条指令 ,
是未定义的行为。
那么下面的代码会产生未定义的行为吗?
for (i=0, j=3, k=1; i<3 && j<9 && k<5; i++, j++, k++) {
printf("%d %d %d\n", i, j, k);
}
因为有 3 条指令用逗号分隔
,
:i++, j++, k++
最佳答案
writing more than 1 instruction separated by comma , is undefined behaviour.
不,这不是一般情况。
在您的情况下,
i++, j++, k++
是完全有效的。FWIW,根据
C11
,第 6.5.17 章,Comma operator (强调我的)The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; [...]
[注意]:您可能会因为看到类似的东西而感到困惑
printf("%d %d %d", i++, ++i, i);
一种声明,但请注意,
,
完全不是逗号运算符(而是提供参数的分隔符)并且不会发生排序。所以,这类陈述是UB。同样,引用标准,同一章节的脚注 3
As indicated by the syntax, the comma operator (as described in this subclause) cannot appear in contexts where a comma is used to separate items in a list (such as arguments to functions or lists of initializers).
关于c - 写 3 条指令是否用逗号分隔 `,` 未定义行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31718412/