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
  • 80,270
  • 14
  • 142
  • 161

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
  • 311
  • 2
  • 8
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
  • 4,041
  • 6
  • 20
  • 37