在C中将(2,6,8)赋给一个整数是什么意思?
下面这段代码的输出是什么?为什么?
#include <stdio.h>
int main()
{
int x = (2,6,8);
printf("%d",x);
return 0;
}
回答
编码
int x = (2, 6, 8);
使用(非常不常见的)逗号运算符。在 C 中,形式的表达式
expr1, expr2, expr3, ..., exprN
被解释为“评估expr1并丢弃其值,然后评估expr2并丢弃其值,......,最后评估exprN并使用其评估为的值”。因此,在您的情况下,该表达式的(2, 6, 8)意思是“评估 2 并丢弃其值,然后评估 6 并丢弃其值,最后评估 8 并使用其值”。这意味着x获取 value 8。
这段代码几乎可以肯定是编写的错误,因为计算 2 和 6 并丢弃它们的值是没有意义的。虽然很少看到逗号运算符,但它最常用于表达式有副作用的上下文中,如
for (x = 0; x < 5; x++, i++) { // Increment both x and i
}
while (x = readValue(), x != 0 && x < 15) { // Read a value into x, then check it
}
- @AndrewTruckle Sure, but you said "the whole concept" 🙂
- @AndrewTruckle Pointless what? The comma operator? Well, it is nice to have a comma operator to have several expressions counted as one (as in the `for` loop example) And then, an operator has to return a value. The choice of the last one is quite arbitrary though.