在C中,三元运算符被定义为
逻辑OR表达?表达式:条件表达式
其中条件表达式定义为
logical-OR-expression
赋值运算符的优先级低于OR运算符.因此你必须写
a >= 5 ? b = 100 : ( b = 200 );
否则编译器会考虑表达式
( a >= 5 ? b = 100 : b ) = 200;
由于C中的三元运算符不是左值,因此上述表达式无效,编译器发出错误.
从C标准:
the result is the value of the second or third operand (whichever
is evaluated),converted to the type described below
和脚注:
110) A conditional expression does not yield an lvalue.
考虑到C和C中的运算符定义之间存在本质区别.在C中它被定义为
逻辑或表达?表达式:赋值表达式
在C中,相同的GCC成功编译代码
#include
int main()
{
int a = 10,b;
a >= 5 ? b = 100 : b = 200;
std::cout << "b = " << b << std::endl;
return 0;
}