c - i = (i,++i, 1) + 1; 是什么意思?做?

标签 c operators expression compiler-warnings comma-operator

看完this answer关于未定义的行为和序列点,我写了一个小程序:

#include <stdio.h>

int main(void) {
  int i = 5;
  i = (i, ++i, 1) + 1;
  printf("%d\n", i);
  return 0;
}

输出是2。天哪,我没有看到减量来了!这里发生了什么?

此外,在编译上述代码时,我收到一条警告:

px.c:5:8: warning: left-hand operand of comma expression has no effect

  [-Wunused-value]   i = (i, ++i, 1) + 1;
                        ^

为什么?但可能会自动回答我的第一个问题。

最佳答案

在表达式 (i,++i, 1) 中,使用的逗号是 comma operator

the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).

因为它丢弃了它的第一个操作数,所以它通常仅在第一个操作数具有理想的副作用时才有用。如果第一个操作数的副作用没有发生,那么编译器可能会生成有关表达式无效的警告。

所以,在上面的表达式中,最左边的 i 将被计算,它的值将被丢弃。然后 ++i 将被评估并将 i 递增 1,表达式 ++i 的值将再次被丢弃,但对 i 的副作用是永久性的。然后将对 1 求值,表达式的值为 1

相当于

i;          // Evaluate i and discard its value. This has no effect.
++i;        // Evaluate i and increment it by 1 and discard the value of expression ++i
i = 1 + 1;  

请注意,上面的表达式是完全有效的,不会调用未定义的行为,因为有一个 sequence point在逗号运算符的左右操作数的评估之间。

关于c - i = (i,++i, 1) + 1; 是什么意思?做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30614396/

相关文章:

c - 如何在 C 中同时打印两个函数?

c - Linux内核: why does this call to kstrtol crash?

c - 重新分配 double 组

c - 父节点在 MPI_Barrier 上停止

javascript - JavaScript 按位运算符如何工作?

c++ - 如何重载 operator< 以将对象放入集合中

javascript - jquery - 尽管条件不满足,为什么 if 子句会触发?

javascript - 将表情符号与文本分开的正则表达式

debugging - 如何创建使用 `expression` 评估其参数的 LLDB 别名

python - 如何在Python中使用正则表达式反转标点符号?