Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why and when does the ternary operator return an lvalue?

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 ; } 
like image 498
Soulimane Mammar Avatar asked Feb 14 '19 10:02

Soulimane Mammar


People also ask

What does ternary operator return?

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.

What is the return type of conditional operators?

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.

What does lvalue mean?

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.

What is lvalue vs rvalue?

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.


1 Answers

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.

like image 188
Some programmer dude Avatar answered Oct 02 '22 03:10

Some programmer dude