编写 3 条指令是否以逗号分隔,未定义行为?
Is writing 3 instructions separated by comma `,` undefined behaviour?
我想我在某处看到用逗号分隔的多条指令 ,
是未定义的行为。
那么下面的代码会产生未定义的行为吗?
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 代码。
有些情况下逗号具有不同的含义,例如在声明语句中。在声明语句中,逗号用于分隔几个变量的声明。
int a;
a = 1,2,3; // Ok. a is assigned the value 3.
int a = 1,2,3; // Not ok!
int a = 1, b = 2; // Ok! a is assigned the value 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 代码。
有些情况下逗号具有不同的含义,例如在声明语句中。在声明语句中,逗号用于分隔几个变量的声明。
int a;
a = 1,2,3; // Ok. a is assigned the value 3.
int a = 1,2,3; // Not ok!
int a = 1, b = 2; // Ok! a is assigned the value 1.