使用在C三元操作错误 [英] Errors using ternary operator in c
问题描述
我有一块用C code给出如下:
I have a piece of code in C given as follows :
main()
{
int a=10, b;
a>=5 ? b=100 : b=200 ;
printf("%d" , b);
}
运行在UNIX gcc编译器的code生成编译时错误的
需要作为分配的左操作数左值,并在乙组分误差为200,而在使用的Turbo C编译窗户给200作为输出。
running the code on gcc compiler in unix generates the compile-time error as 'lvalue required as left operand of assignment' and points the error at b = 200 whereas in windows compiling using Turbo C gives 200 as output.
有人能解释一下究竟是什么在这种情况下发生?
Can anybody please explain what exactly is happening in this case ?
推荐答案
在C中的三元运算符如
逻辑或-EX pression?前pression:有条件-EX pression
logical-OR-expression ? expression : conditional-expression
其中的条件前pression 的的定义如下
where conditional expression is defined like
logical-OR-expression
赋值运算符比OR运算符优先级较低。因此,你必须写
The assignment operator has a lower priority than the OR operator. Thus you have to write
a >= 5 ? b = 100 : ( b = 200 );
否则编译器consideres除权pression像
Otherwise the compiler consideres the expression like
( a >= 5 ? b = 100 : b ) = 200;
在C语言中三元运算符的结果不是左值那么上述前pression无效,编译器会发出错误。
As the result of the ternary operator in C is not an lvalue then the above expression is invalid and the compiler issues an error.
从C标准:
结果是第二个或第三个操作数的值(取
被评估),转换为下面
the result is the value of the second or third operand (whichever is evaluated), converted to the type described below
和脚注:
110)有条件的前pression不会产生左值。
110) A conditional expression does not yield an lvalue.
要考虑到有在C和C ++操作定义之间的本质区别。在C ++中,它被定义为
Take into account that there is an essential difference between the operator definition in C and C++. In C++ it is defined as
逻辑或-EX pression?前pression:分配-EX pression
logical-or-expression ? expression : assignment-expression
在C ++中相同的GCC编译code成功
In C++ the same GCC compiles the code successfully
#include <iostream>
int main()
{
int a = 10, b;
a >= 5 ? b = 100 : b = 200;
std::cout << "b = " << b << std::endl;
return 0;
}
这篇关于使用在C三元操作错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!