Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
770 views
in Technique[技术] by (71.8m points)

gcc - Errors using ternary operator in c

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);
}

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In C the ternary operator is defined like

logical-OR-expression ? expression : conditional-expression

where conditional expression is defined like

logical-OR-expression

The assignment operator has a lower priority than the OR operator. Thus you have to write

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

Otherwise the compiler consideres the expression like

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

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.

From the C Standard:

the result is the value of the second or third operand (whichever is evaluated), converted to the type described below

and footnote:

110) A conditional expression does not yield an lvalue.

Take into account that there is an essential difference between the operator definition in C and C++. In C++ it is defined as

logical-or-expression ? expression : assignment-expression

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...