c - 写 3 条指令是否用逗号分隔 `,` 未定义行为?

标签 c undefined-behavior comma-operator

我想我在某处看到了用逗号分隔的多于 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/

相关文章:

c - 使用递归函数反向打印链表

c - 从recv返回填充有二进制数据的缓冲区

c++ - 如果可能存在未定义行为,为什么编译器不警告您?

c - 逗号运算符 , 有什么作用?

c++ - void()、逗号运算符 (operator,) 和不可能的 (?) 重载

c - 简单的 c 数组计算器删除第一个数字

c - 访问结构数组时抛出异常

c - 如何鼓励 C 程序中的未定义行为/乱序执行?

c++ - 如何在没有未定义行为的情况下修改 float/double 的位?

c++ - 为什么允许某些非常量表达式作为 constexpr 逗号运算符的操作数?