三元和逗号运算符
Ternary and comma operator
int a,b;
a = 1 ? 1,2 : 3,4; // a = 2
b = 0 ? 1,2 : 3,4; // b = 3
逗号运算符 returns 始终在逗号的右侧,但是如果我们对变量赋值 returns 左侧,除非我们使用 ().
那么第一个表达式到底是怎么给出 2.
我认为它是 a = 1,2 所以它应该是 1 但实际上是 a=2。
为什么?
由于operator precedence(逗号运算符的优先级最低),您的代码实际上看起来像
int a,b;
(a = 1 ? (1,2) : 3),4; // a = 2
(b = 0 ? (1,2) : 3),4; // b = 3
因此,根据三元条件规则,引用 C11
,章节 §6.5.15
The first operand is evaluated; there is a sequence point between its evaluation and the
evaluation of the second or third operand (whichever is evaluated). The second operand
is evaluated only if the first compares unequal to 0; the third operand is evaluated only if
the first compares equal to 0; the result is the value of the second or third operand
(whichever is evaluated), converted to the type described below. 110)
[...]
110) A conditional expression does not yield an lvalue.
- 对于第一种情况,计算并返回第二个操作数。
- 对于第二种情况,计算并返回第三个操作数。
int a,b;
a = 1 ? 1,2 : 3,4; // a = 2
b = 0 ? 1,2 : 3,4; // b = 3
逗号运算符 returns 始终在逗号的右侧,但是如果我们对变量赋值 returns 左侧,除非我们使用 (). 那么第一个表达式到底是怎么给出 2.
我认为它是 a = 1,2 所以它应该是 1 但实际上是 a=2。
为什么?
由于operator precedence(逗号运算符的优先级最低),您的代码实际上看起来像
int a,b;
(a = 1 ? (1,2) : 3),4; // a = 2
(b = 0 ? (1,2) : 3),4; // b = 3
因此,根据三元条件规则,引用 C11
,章节 §6.5.15
The first operand is evaluated; there is a sequence point between its evaluation and the evaluation of the second or third operand (whichever is evaluated). The second operand is evaluated only if the first compares unequal to 0; the third operand is evaluated only if the first compares equal to 0; the result is the value of the second or third operand (whichever is evaluated), converted to the type described below. 110)
[...]
110) A conditional expression does not yield an lvalue.
- 对于第一种情况,计算并返回第二个操作数。
- 对于第二种情况,计算并返回第三个操作数。