C vs C ++中的三元运算符 [英] Ternary operator in C vs C++

查看:142
本文介绍了C vs C ++中的三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C和C ++之间有很多区别,并且卡在其中一个
上。同一代码在C中出现错误,而在C ++
中可以正常执行,请解释原因

There are a lot of differences between C and C++ and came to stuck on one of them The same code gives an error in C while just executes fine in C++ Please explain the reason

int main(void)
{
   int a=10,b;
   a>=5?b=100:b=200;
}

上面的代码在 C 中指出错误需要 lvalue ,而相同的代码在 C ++

The above code gives an error in C stating lvalue required while the same code compiles fine in C++

推荐答案

具有

在没有显式()的情况下,代码的行为类似于

Without an explicit () your code behaves like

( a >= 5 ? b = 100 :  b ) = 200;

?:表达式的结果是不是可修改的左值 [#] ,因此我们无法为其分配任何值。

The result of a ?: expression is not a modifiable lvalue [#] and hence we cannot assign any values to it.

值得一提的是,根据 c 语法规则,

Also, worthy to mention, as per the c syntax rule,


绝对不允许赋值出现在条件运算符的右侧

assignment is never allowed to appear on the right hand side of a conditional operator

相关参考文献:C优先级表

OTOH,如果 c ++ 很好,

OTOH, In case of c++, well,


条件运算符的优先级与赋值相同。

the conditional operator has the same precedence as assignment.

并从右到左进行分组,本质上使您的代码表现为

and are grouped right-to-left, essentially making your code behave like

 a >= 5 ? (b = 100) : ( b = 200 );

因此,在 c ++

[#]-根据6.5.15章的脚注(12), C99 标准,

[ # ] -- As per chapter 6.5.15, footnote (12), C99 standard,


条件表达式不会产生左值。

A conditional expression does not yield an lvalue.

这篇关于C vs C ++中的三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆