c - "return i++, i, i++;"在 C 中是未定义的行为吗?

标签 c language-lawyer undefined-behavior c11

如果我这样写:

i = i++, i, i++;

这是 C 语言中的未定义行为

但是,如果我这样写:

return i++, i, i++; // Is it UB?

这是未定义的行为吗?

示例:

#include <stdio.h>

int f(int i)
{
    return i++, i, i++; // Is it UB?
}
int main() {
    int i = 1;
    i = i++, i, i++;

    i = f(i);
    printf("%d\n",i);
    return 0;
}

最佳答案

i = i++, i, i++; 是 UB,因为 = 的优先级高于 ,,因此表达式被解析为 (i = i++), i, i++,其中子表达式 i = i++ 调用 UB1)

即使代码被写成i = (i++, i, i++);,它仍然是UB,因为现在之间没有序列点最右边的 i++i= 的左操作数 1)

但是,当您删除 i = 部分时,您就删除了该不明确的行为。 return i++, i, i++; 必须排序为:

i++, the left one
sequence point from left comma
i
sequence point from right comma
i++, the right one
sequence point before returning

所以它是明确定义的。

<小时/>

来源:

1) C11 6.5/2

If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined. If there are multiple allowable orderings of the subexpressions of an expression, the behavior is undefined if such an unsequenced side effect occurs in any of the orderings.

然后还有 C11 6.5.16/3

The side effect of updating the stored value of the left operand is sequenced after the value computations of the left and right operands. The evaluations of the operands are unsequenced.

值得注意的是,上述有关赋值的文本在 C11 和 C++11 之间是不同的。

关于c - "return i++, i, i++;"在 C 中是未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47264258/

相关文章:

c - 将 const char** 传递给函数 - 如何构建 char**?

c++ - 读取和比较 POD 类型的填充字节是未定义的行为吗?

c++ - 括号是否会创建非推导上下文?

c - 在字符串文字中使用哪些字符是合法的?

c++ - 为什么无符号和有符号相减后符号不同?

c - C语言中free的奇怪(未定义?)行为

c++ - 未定义行为 : value of array element changes implicitly/illogically

c - 使用文件运行程序时出现问题

c - 为什么 gcc 和 clang 不警告库函数的未使用结果?

c - 我的堆栈实现有什么问题?