<分区>
C 和 C++ 之间有很多差异,并且卡在其中之一 相同的代码在 C 中出错,而在 C++ 中执行良好 请说明原因
int main(void)
{
int a=10,b;
a>=5?b=100:b=200;
}
上面的代码在 C 中给出了一个错误,指出 lvalue 是必需的,而相同的代码在 C++ 中编译得很好
<分区>
C 和 C++ 之间有很多差异,并且卡在其中之一 相同的代码在 C 中出错,而在 C++ 中执行良好 请说明原因
int main(void)
{
int a=10,b;
a>=5?b=100:b=200;
}
上面的代码在 C 中给出了一个错误,指出 lvalue 是必需的,而相同的代码在 C++ 中编译得很好
最佳答案
查看运算符优先级。
没有显式的 ()
你的代码表现得像
( a >= 5 ? b = 100 : b ) = 200;
?:
表达式的结果不是可修改的左值 [#] 因此我们不能赋值 它的任何值。
此外,值得一提的是,根据 c
语法规则,
assignment is never allowed to appear on the right hand side of a conditional operator
相关引用:C precedence table .
OTOH,在 c++
的情况下,嗯,
the conditional operator has the same precedence as assignment.
并且从右到左分组,本质上使您的代码表现得像
a >= 5 ? (b = 100) : ( b = 200 );
因此,您的代码在 c++
[ # ] -- 根据第 6.5.15 章,脚注 (12),C99
标准,
A conditional expression does not yield an lvalue.
关于c++ - C 与 C++ 中的三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28337054/