Registered User
Registered User

Reputation: 5361

syntax of comparison between two different things

Following program gives error

#include<stdio.h>
int main ()
{
int a=10,b;
a>=5?b=100:b=200;
printf("\n%d",b);
}

the error is

ka1.c: In function ‘main’:
ka1.c:5: error: lvalue required as left operand of assignment

now if I replace the line

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

by

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

and then compile then there is no error. So I wanted to know what is wrong with

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

Upvotes: 2

Views: 873

Answers (3)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

The ternary operator (?:) has higher precedence than the assignment operator (=). So your original statement is interpreted as:

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

Write it like this instead:

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

This is idiomatic C. (The brackets around the condition are not really necessary, but they aid readability.)

Upvotes: 10

Michael Lowman
Michael Lowman

Reputation: 3068

You're using the ternary operator incorrectly. Both of your examples are wrong, even though one compiles. The expression evaluates to either the second or third sub-expression depending upon the truth value of the first.

So a ? b : c will be the same thing as b if a is true, or c if a is false.

The proper way of using this operator is to assign the result to a variable:

b = a>= 5 ? 100 : 200;

Upvotes: 3

Mariy
Mariy

Reputation: 5914

Because it tries to do: (a>=5?b=100:b)=200 But the thing in parentheses is not lvalue.

Upvotes: 1

Related Questions