4

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

r.bhardwaj
  • 1,603
  • 6
  • 28
  • 54

3 Answers3

5

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.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
2

The issue you encounter is operator precedence. The = operator has lower precedence than the ?: operator.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • Do you mean "The = operator has LOWER precedence than ?:". Because first the ?: is executed, then the assignment. – poitroae Aug 19 '12 at 09:54
2

I think your code should be:

int main()  
{  
      int a=2,b=3; 

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

      printf("%d",b);  
      return 0;     
}

Cheers.

Azurlake
  • 612
  • 1
  • 6
  • 29