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?
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 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.
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.
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