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?
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
is not legal in Standard C++ either.
In general, though, it is legal to initialize a
constreference 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-constreference with an lvalue of the right type, which the conditional operator yields under certain conditions.