Assignment statement used in conditional operators

后端 未结 6 1700
执念已碎
执念已碎 2020-12-07 02:12

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

         


        
6条回答
  •  萌比男神i
    2020-12-07 02:50

    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
    

提交回复
热议问题