The concept of a ternary operator (? :) In c

When compiling this program into the GCC Compiler :

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


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

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

Then it does not show a compilation error. Can someone explain to me why?
And also how is this different from if ... else ...?

+4
source share
3 answers

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

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

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

The code can be more clearly written as:

 b = a > 1 ? 10 : 50; 

And how is it different from if ... else ...?

The conditional operator only works with expressions as operands. The if may contain instructions in the body.

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

+5
source

The problem you are facing is operator priority. The = operator has lower precedence than the ?: Operator.

+2
source

I think your code should be:

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

Greetings.

+2
source

All Articles