0

This code throws an lvalue required compile time error.

#include <stdio.h>

void main()
{
    int k = 8;
    int m = 7;
    k < m ? k++ : m = k;
    printf("%d", k);
}
Inian
  • 71,145
  • 9
  • 121
  • 139

2 Answers2

1

Ternary operator has higher precedence than assignment, that's why your code is equal to (k < m ? k++ : m) = k;. Your compiler says that the value in brackets is not assignable.

What you want to do is:

#include <stdio.h>

void main()
{
    int k = 8;
    int m = 7;
    k < m ? k++ : (m = k);
    printf("%d", k);
}
alexsakhnov
  • 116
  • 1
  • 7
0

The problem is here:

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

with the construct you want to assign a value, but you don't. I guess you want something like this:

   k =  (k < m) ? k+1 : m;

Now you will assign k a value depending on the condition k < m

if (k < m) -> k = k+1
otherwise -> k = m

Mike
  • 3,738
  • 5
  • 18
  • 36