Him*_*wal 2 c c++ variables conditional-operator lvalue
我的代码是:
#include<stdio.h>
int main() {
int a=10, b;
a >= 5 ? b=100 : b=200;
printf("%d %d", a, b);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这里出现了条件运算符行中的"Lvalue Required".
你能解释一下为什么吗?
顺便说一句,相同的程序完全适用于C++.
编写该作业的惯用方法是:
b = (a >= 5) ? 100 : 200;
Run Code Online (Sandbox Code Playgroud)
如果您坚持按自己的方式保留,请添加括号:
(a >= 5) ? (b=100) : (b=200);
Run Code Online (Sandbox Code Playgroud)
有关为何在C++中有效但在C中无效的详细信息,请参阅C和C++之间的条件运算符差异(感谢@Grijesh Chauhan!)