This question already has an answer here:
- Errors using ternary operator in c 5 answers
There are a lot of differences between C and C++ and came to stuck on one of them The same code gives an error in C while just executes fine in C++ Please explain the reason
int main(void)
{
int a=10,b;
a>=5?b=100:b=200;
}
The above code gives an error in C stating lvalue required while the same code compiles fine in C++
Because C and C++ aren't the same language, and you are ignoring the assignment implied by the ternary. I think you wanted
which should work in both C and C++.
Have a look at the operator precedence.
Without an explicit
()
your code behaves likeThe result of a
?:
expression is not a modifiable lvalue [#] and hence we cannot assign any values to it.Also, worthy to mention, as per the
c
syntax rule,Relared Reference : C precedence table.
OTOH, In case of
c++
, well,and are grouped right-to-left, essentially making your code behave like
So, your code works fine in case of
c++
[ # ] -- As per chapter 6.5.15, footnote (12),
C99
standard,In C you can fix it with placing the expression within Parentheses so that while evaluating the assignment becomes valid.
The error is because you don't care about the operator precedence and order of evaluation.