Assignment statement used in conditional operators

c

Solution

In the expression,

(a > b ? g = a : g = b);

the relational operator `>` has the highest precedence, so `a > b` is grouped as an operand. The conditional-expression operator `? :` has the next-highest precedence. Its first operand is `a>b`, and its second operand is `g = a`. However, the last operand of the conditional-expression operator is considered to be `g` rather than `g = b`, since this occurrence of `g` binds more closely to the conditional-expression operator than it does to the assignment operator. A syntax error occurs because `= b` does not have a left-hand operand (l-value). You should use parentheses to prevent errors of this kind and produce more readable code which has been done in your second statement

(a > b ? g = a : (g = b));

in which last operand `g = b` of `: ?` has an l-value `g` and thats why it is correct.

Alternatively you can do

g = a > b ? a : b

Problem

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 ``` (a>b?g=a:(g=b)); ``` where `a , b` and `g` are integer variables , and `a` and `b` are taken as input from keyboard.

Original source

Related problems