我想知道C语言中的三元运算符是否所有参数都是强制性的? 例如:
(exp1 ? : value2);
或者你需要写:
(expr1 ? value1: value2);
我问这个是因为如果你写:(exp1 ? : value2);
如果 expr1
为 TRUE 会返回什么?
最佳答案
这不是标准,而是GCC extension (可能其他一些编译器也这样做):
5.7 Conditionals with Omitted Operands
The middle operand in a conditional expression may be omitted. Then if the first operand is nonzero, its value is the value of the conditional expression.
Therefore, the expression
x ? : y
has the value of x if that is nonzero; otherwise, the value of y.
This example is perfectly equivalent to
x ? x : y
编辑:
正如@MadPhysicist 指出的那样,缩短的形式将评估 x
一次,而传统形式会重新评估 x
第二次x
不为零
关于c - 三元运算符中的所有参数都是强制性的还是你可以做 "(exp1 ? : value)"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39232537/