两个不同事物之间比较的语法
以下程序给出错误,
#include<stdio.h>
int main ()
{
int a=10,b;
a>=5?b=100:b=200;
printf("\n%d",b);
}
那么
ka1.c: In function ‘main’:
ka1.c:5: error: lvalue required as left operand of assignment
如果我替换该行然后编译,则错误是现在
a>=5?b=100:b=200;
,
a>=5?b=100:(b=200);
就没有错误。 所以我想知道出了什么问题
a>=5?b=100:b=200;
Following program gives error
#include<stdio.h>
int main ()
{
int a=10,b;
a>=5?b=100:b=200;
printf("\n%d",b);
}
the error is
ka1.c: In function ‘main’:
ka1.c:5: error: lvalue required as left operand of assignment
now if I replace the line
a>=5?b=100:b=200;
by
a>=5?b=100:(b=200);
and then compile then there is no error.
So I wanted to know what is wrong with
a>=5?b=100:b=200;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
三元运算符 (
?:
) 具有更高的优先级 比赋值运算符 (=
) 更重要。所以你原来的陈述被解释为:像这样写:
这是惯用的C。(条件周围的括号并不是真正必要的,但它们有助于可读性。)
The ternary operator (
?:
) has higher precedence than the assignment operator (=
). So your original statement is interpreted as:Write it like this instead:
This is idiomatic C. (The brackets around the condition are not really necessary, but they aid readability.)
您错误地使用了三元运算符。你的两个例子都是错误的,即使其中一个可以编译。该表达式计算为第二个或第三个子表达式,具体取决于第一个子表达式的真值。
那么
a ? b : c
如果a
为 true,则与b
相同,如果a
则与c
相同> 是假的。使用此运算符的正确方法是将结果分配给变量:
You're using the ternary operator incorrectly. Both of your examples are wrong, even though one compiles. The expression evaluates to either the second or third sub-expression depending upon the truth value of the first.
So
a ? b : c
will be the same thing asb
ifa
is true, orc
ifa
is false.The proper way of using this operator is to assign the result to a variable:
因为它尝试执行以下操作:
(a>=5?b=100:b)=200
但括号里的东西不是左值。
Because it tries to do:
(a>=5?b=100:b)=200
But the thing in parentheses is not lvalue.