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… ?
As mentioned in the comments, you have an issue with operator precedence. Your code is interpreted as follows:
The above code is invalid for the same reason that writing
(b = 10) = 50is invalid.The code can be more clearly written as:
The conditional operator works only with expressions as operands. An
ifstatement can contain statements in the body.A conditional operator can always be replaced by an equivalent
ifstatement. But the reverse is not true – there are if statements that cannot be replaced with an equivalent conditional operator expression.