1

visual studio does not report any error for this program while turbo c/c++ says 'Lvalue required in function main'

int main()
{
  int a=10,b; 
  a>=5?b=100:b=200;
  printf("%d",b);
  return 0;

}

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

why is it so ? explain.

Michelle
  • 2,830
  • 26
  • 33
dcoder11
  • 31
  • 4
  • There's an answer with a good explanation, but for the sake of readability, I'd recommend you change it to `b = (a>=5?100:200);` – Michelle Aug 13 '13 at 13:23

3 Answers3

5

In C++, the ternary conditional operator takes an assignment-expression as it's third operand, so your expression is understood as:

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

In the "true" case this amounts to:

b = 100 = 200;

This in turn groups right-to-left, i.e.:

b = (100 = 200);

This clearly doesn't make sense.


What you meant to say is:

if (a >= 5) { b = 100; } else { b = 200; }

You don't need an expression; a statement is perfectly fine. Alternatively, as Michelle suggests:

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

Note that the ternary conditional operator is different in C, although it looks similar!

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • 1
    @DrewMcGowen: That depends what you expect of your compiler. Visual Studio speaks its own dialect that isn't really proper C++... – Kerrek SB Aug 13 '13 at 13:22
1

According to the standard C syntax this ternary expression must be parsed as if it was:

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

The workaround is adding parentheses, like you have done, or using an if-statement, or writing the expression as

b = a>=5? 100: 200;

The C++ language has slightly different syntax rules that make the expression parse the way you expect. It sounds like turbo c/c++ is following C rules white visual studio is applying C++ rules. See also: Conditional operator differences between C and C++

Community
  • 1
  • 1
Joni
  • 108,737
  • 14
  • 143
  • 193
1

On line 4 your code a>=5?b=100:b=200; is half an expression.

The C tenernary operator ?: yields an lvalue expression i.e. an expression with a result. It can be thought of as analogous to a function return, but the value is not silently discarded in this case.

think of the ?: operator as result = if(test evaluates to true)then this else that where then is the ? and else is the :

You should therefore rewrite the line as b = (a>=5)?100:200; or

if (a >=5)     //test
{              //'?'
    b = 100;  
}
else
{          //':'
    b = 200
}