1

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

This particular expression gives compile time error saying lvalue required. The problem is with k++. Not able to understand what is wrong in this expression.

Alex K.
  • 171,639
  • 30
  • 264
  • 288

1 Answers1

5

The input

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

is parsed as

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

where k++ is an rvalue and m is an lvalue. So the conditional is an rvalue.

You probably mean something like

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

Better use

if (k < m) {
    k++;
} else {
    m = k;
}

instead.

You can see the C precedence table e.g. here: http://en.cppreference.com/w/c/language/operator_precedence.

The terms "lvalue" and "rvalue" mostly mean "things that you can write left of an assignment" and "things you can only write on the right side of an assignment", resp. C.f. "Are literal strings and function return values lvalues or rvalues?".


An easier example to see the semantics of ?:: For a uint8_t k, what does condition ? k : k + 1 mean?

  • Easy to see the former part k is an lvalue with the type uint8_t.

  • The latter expression k + 1 is somewhat trickier, though. Being the result of an arithmetic expression, it is an rvalue. Also it's not a uint_8 but int.

  • The common type of uint8_t and int is int. So in total condition ? k : k + 1 is an rvalue expression with the type int.

Community
  • 1
  • 1
Kijewski
  • 25,517
  • 12
  • 101
  • 143
  • Thanks a lot.Any links where I could learn more about precedence and lvalue, rvalue so I dont make such mistakes? – HimanshuSingh Oct 21 '14 at 16:35
  • E.g. [cppreference.com](http://en.cppreference.com/w/c/language/operator_precedence) has a list of the operator precedences. "lvalue" and "rvalue" mostly means "things that you can write left of an assignment" and "things you can *only* write on the right side of an assignment", resp. C.f. http://stackoverflow.com/q/2038414/416224 – Kijewski Oct 21 '14 at 16:41