看完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/