Question

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.

Was it helpful?

Solution

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!

OTHER TIPS

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
}

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++

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top