I have :
#include<stdio.h>
int main()
{
int a=5,b=6;
(a>b)?b=a:b=b; // Here is the error
return 0;
}
But if I replace :
(a>b)?b=a:b=b; // Error
with
(a>b)?(b=a):(b=b); // No-Error
I understand the lvalue
is a value to which something can be assigned and how is it different from rvalue
, but why is the extra parenthesis
making the difference.
When we put an equation in parenthesis it is treated as an expression. And it returns some value which provide solution to the error.
It is really:
Note: you should simply
Assignment has a lower precedence than the ternary operator so the line evaluates like:
use:
Actually, in C, this code
is parsed by many compilers as
which is an error, as the expression
((a>b)?b=a:b)
evaluates to an rvalue which you try to assign withb
which results in an error. Trying to assign an rvalue is an error. If it is not parsed that way, then its simply a syntax error. But a C compiler is NOT allowed to parse it as:Because the grammar of C does not allow a compiler to parse the code as above.
But what you've written (the original code) is correct as C++.
Here the grammars of C and C++ differ a lot. And because of that difference you see both languages treat the expression differently. That is,
the conditional expression in C++
is different fromthe conditional expression in C
.Wikipedia has very good and correct explanation for this: