Why and When the ternary operator returns an lvalue

  • A+

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 ; }  


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.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: