Can anybody please tell me why this statement is giving an error - Lvalue Required
(a>b?g=a:g=b);
but this one is correct
The problem is operator precedence: In C the ternary conditional operator (?:
) has a higher precedence than the assignment operator (=
).
Without parenthesis (which don't do anything here) your expression would be this:
a > b ? g = a : g = b;
The operator with the highest precedence in there would be the comparison >
, so this is where you'll get your first logical grouping:
(a > b) ? g = a : g = b;
The next highest expression is the ternary conditional, which results in the following expression:
((a > b) ? (g = a) : (g)) = b;
As you can see, you'll now end up with an lvalue (i.e. a value; not a variable) on the left side of your assignment operator, something that won't work.
As you already noticed, the solution to this is to simply group the expressions on your own. I'd even consider this good practice, especially if you're unsure how your precedence might play out. If you don't want to think about it, add parenthesis. Just keep code readability in mind, so if you can, resolve the operator precedence on your own, to ensure you've got everything right and readable.
As for readability: I'd probably use a classic if()
here or move the assignment operator outside the ternary conditional, which is how you usually define max()
:
g = a > b ? a : b;
Or more general as a macro or inline function:
#define max(a, b) ((a) > (b) ? (a) : (b))
inline int max(int a, int b) {
return a > b ? a : b;
}