Initializing reference variables with the conditional if else operator

The ternary operator does not expand to an if-else construct (not according to the language, the implementation might generate equivalent binaries, but at the language level they are different). So the following code is valid:

int four = 4, five = 5;
int& r = condition? four : five;

The original example in the question depends on a Microsoft extension that (incorrectly) allows binding a non-const reference to an rvalue expression.


The code you posted does not compile with VC++ 2010:

Error 1 error C2440: 'initializing' : cannot convert from 'int' to 'int &'

Changing the line to:

const int& a = isfive ? 5 : 4; 

makes it compile.


The conditional operator is an expression, not a statement. It is perfectly fine to initialise a reference like that. It's a little like initialising a reference by calling a function.

Note that your reference needs to be const if you bind it to temporaries (a rule which MSVC++ stupidly ignores).


MSVC has a non-standard "extension". What it means is that it allows broken code. There's a good reason this is prohibited.

Note also that

int& a = 5;

is not legal in Standard C++ either.

In general, though, it is legal to initialize a const reference with any expression which can be converted to the right type (including use of the conditional operator). And it is legal to initialize a non-const reference with an lvalue of the right type, which the conditional operator yields under certain conditions.