Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Errors using ternary operator in c

Tags:

c

gcc

turbo-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 ?

like image 658
user3778845 Avatar asked Oct 19 '14 08:10

user3778845


People also ask

Why we should not use ternary operator?

Except in very simple cases, you should discourage the use of nested ternary operators. It makes the code harder to read because, indirectly, your eyes scan the code vertically. When you use a nested ternary operator, you have to look more carefully than when you have a conventional operator.

Can you throw an error in a ternary?

No, it's absolutely not allowed. throw is a statement and it can't be part of an expression.

Is using ternary operator bad practice?

The conditional ternary operator can definitely be overused, and some find it quite unreadable. However, I find that it can be very clean in most situations that a boolean expression is expected, provided that its intent is clear.

How do I check my ternary operator condition?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.


1 Answers

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;
}
like image 139
Vlad from Moscow Avatar answered Sep 24 '22 00:09

Vlad from Moscow