Assignment statement used in conditional operators

后端 未结 6 1694
执念已碎
执念已碎 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条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-07 02:54

    The expression:

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

    parsed as:

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

    And we can't assign to an expression so its l-value error.

    Read: Conditional operator differences between C and C++ Charles Bailey's answer:

    Grammar for ?: is as follows:

    conditional-expression:
        logical-OR-expression
        logical-OR-expression ? expression : conditional-expression
    

    This means that a ? b : c = d parses as (a ? b : c) = d even though (due to the 'not an l-value' rule) this can't result in a valid expression.

    One side note:

    Please keep space in you expression so that it become readable for example.

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

    Should be written as:

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

    similarly, you should add space after ; and ,.

提交回复
热议问题