(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.
(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.
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
.