0
    #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?
Pankaj Mahato
  • 1,051
  • 5
  • 14
  • 26

1 Answers1

4

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++

Community
  • 1
  • 1
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208