三元运算符,如果我避免写“表达式 2”,它可以工作,但如果我不写 'expression 3 ',它会出错

Ternary operator, if I avoid writing ' expression 2 ' it works but if I not write 'expression 3 ' it gives an error

代码

#include<iostream>

int main()
{
    int a=4,b,c;
    a==3 ? : b=a*a ;     // Works fine
    a==4 ? c=a*a : ;     // ERROR Expected Primary expression before ;
}

那么为什么它在“表达式 2”和“表达式 3”中有所区别?

这在 GNU C/C++ 中受支持,称为 Elvis operator。它在标准 C++ 中是不允许的(例如 MSVC++ 不支持它)。

official documentation

中有描述

6.8 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

In this simple case, the ability to omit the middle operand is not especially useful. When it becomes useful is when the first operand does, or may (if it is a macro argument), contain a side effect. Then repeating the operand in the middle would perform the side effect twice. Omitting the middle operand uses the value already computed without the undesirable effects of recomputing it.