Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concept of ternary operator (? : ) in c [duplicate]

On compiling given program in GCC Compiler :

int main()  
{  
      int a=2,b=3;  
      (a>1)?b=10:b=50;  
      printf("%d",b);  
      return 0;     
}


it is showing error that "lvalue required as left operand"
but if i write 4th line as

(a>1)?b=10:(b=50);

Then its showing no compilation error . Can any one explain me why ?
And also how does it differ from if...else... ?

like image 754
r.bhardwaj Avatar asked Jan 15 '23 19:01

r.bhardwaj


1 Answers

As mentioned in the comments, you have an issue with operator precedence. Your code is interpreted as follows:

((a > 1) ? b = 10 : b) = 50;

The above code is invalid for the same reason that writing (b = 10) = 50 is invalid.

The code can be more clearly written as:

b = a > 1 ? 10 : 50;

And also how does it differ from if...else... ?

The conditional operator works only with expressions as operands. An if statement can contain statements in the body.

A conditional operator can always be replaced by an equivalent if statement. But the reverse is not true - there are if statements that cannot be replaced with an equivalent conditional operator expression.

like image 176
Mark Byers Avatar answered Jan 25 '23 08:01

Mark Byers