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:
((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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With