Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing reference variables with the conditional if else operator

The following C++ is invalid because reference variables require initializers:

int& a; // illegal
if (isfive) {
  a = 5;
} else {
  a = 4;
}

However, MSVC seems to think this is okay:

int& a = isfive ? 5 : 4;

This implies to me that MSVC is actually treating the conditional operator like a single expression and not expanding it into an if-else statement.

Is it always valid C++ to initialize a reference using the conditional operator?

like image 544
Kai Avatar asked Feb 08 '12 19:02

Kai


3 Answers

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.

like image 64
Nemanja Trifunovic Avatar answered Oct 13 '22 12:10

Nemanja Trifunovic


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.

like image 12
David Rodríguez - dribeas Avatar answered Nov 17 '22 00:11

David Rodríguez - dribeas


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.

like image 5
Ben Voigt Avatar answered Nov 17 '22 01:11

Ben Voigt