Search code examples
cshorthand-if

Why lvalue is required in shorthand if-else in the else part when using a assignment operator?


    #include <stdio.h>

    void main()
    {
        int k = 8;
        int m = 7;
        int z = k < m ? k = m : m++;
        printf("%d", z);

        k = 8;
        m = 7;
        z = k < m ? m++ : k=m;
        printf("%d", z);
    }

Output

Compile Error:
main.c: In function 'main':
main.c:19:32: error: lvalue required as left operand of assignment
         z = k < m ? m++ : k=m;
                            ^
  • Why the first assignment works and second doesn't?
  • And why the compiler tells that lvalue is required?

Solution

  • Due to higher precedence of ?: conditional operator in comparison to =

    z = k < m ? m++ : k=m;
    

    Is equivalent to (or say parse as):

    z = ((k < m ? m++ : k) = m);
    //    ^^^^^^^^^^^^^^^^            
    //    expression       = m 
    

    m is assigned to an expression that is - Lvalue error.

    Read Conditional operator differences between C and C++