For a long time I thought that the ternary operator always returns an rvalue. But to my surprise it doesn't. In the following code I don't see the difference between the return value of foo
and the return value of the ternary operator.
#include <iostream> int g = 20 ; int foo() { return g ; } int main() { int i= 2,j =10 ; foo()=10 ; // not Ok ((i < 3) ? i : j) = 7; //Ok std::cout << i <<","<<j << "," <<g << std::endl ; }
The ternary operator is used to return a value based on the result of a binary condition. It takes in a binary condition as input, which makes it similar to an 'if-else' control flow block. It also, however, returns a value, behaving similar to a function.
Conditional AND The operator is applied between two Boolean expressions. It is denoted by the two AND operators (&&). It returns true if and only if both expressions are true, else returns false.
An lvalue (locator value) represents an object that occupies some identifiable location in memory (i.e. has an address). rvalues are defined by exclusion. Every expression is either an lvalue or an rvalue, so, an rvalue is an expression that does not represent an object occupying some identifiable location in memory.
An lvalue refers to an object that persists beyond a single expression. An rvalue is a temporary value that does not persist beyond the expression that uses it.
Both i
and j
are glvalues (see this value category reference for details).
Then if you read this conditional operator reference we come to this point:
4) If E2 and E3 are glvalues of the same type and the same value category, then the result has the same type and value category
So the result of (i < 3) ? i : j
is a glvalue, which can be assigned to.
However doing something like that is really not something I would recommend.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With