在有条件的经营者使用赋值语句 [英] Assignment statement used in conditional operators

查看:213
本文介绍了在有条件的经营者使用赋值语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我,为什么这句话给了一个错误 - 左值要求

Can anybody please tell me why this statement is giving an error - Lvalue Required

(a>b?g=a:g=b); 

但是这一次是正确的。

but this one is correct

(a>b?g=a:(g=b));

其中, A,B 先按g 是整型变量, A b 被当作从键盘输入。

where a , b and g are integer variables , and a and b are taken as input from keyboard.

推荐答案

在除权pression,

In the expression,

(a > b ? g = a : g = b);

关系运算符> 具有最高的precedence,所以 A> b 进行分组作为一个操作数。有条件的-EX pression运营商有一个最高precedence。它的第一个操作数是 A> b ,它的第二个操作数 G = A 。然而,有条件的-EX pression运营商的最后一个操作数被认为是先按g ,而不是 G = B ,因为这发生先按g 的更紧密地结合到有条件-EX pression运营商比它赋值运算符的。因为 = B 没有左手操作数(L值)时发生语法错误。结果
你应该使用括号这样的prevent错误并产生更具可读性code已在您的第二份声明已经完成

the relational operator > has the highest precedence, so a > b is grouped as an operand. The conditional-expression operator ? : has the next-highest precedence. Its first operand is a>b, and its second operand is g = a. However, the last operand of the conditional-expression operator is considered to be g rather than g = b, since this occurrence of g binds more closely to the conditional-expression operator than it does to the assignment operator. A syntax error occurs because = b does not have a left-hand operand (l-value).
You should use parentheses to prevent errors of this kind and produce more readable code which has been done in your second statement

(a > b ? g=a : (g = b));

在过去的操作数 G = B 有一个左值键,这就是为什么它是正确的。

in which last operand g = b of : ? has an l-value g and thats why it is correct.

阅读秩序/ A>了解更多详情。

Read about order of evaluation, associativity and operator precedence for more detail.

这篇关于在有条件的经营者使用赋值语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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