Initialization of control variables with a conditional statement

The following C ++ is not valid because reference variables require initializers:

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

However, it seems MSVC thinks this is normal:

 int& a = isfive ? 5 : 4; 

This means that MSVC actually treats the conditional statement as a single expression and does not extend it into an if-else statement.

Is C ++ always initializing a link using a conditional statement?

+6
source share
6 answers

MSVC has a non-standard "extension". This means that it allows you to break the code. There is a good reason this is forbidden.

We also note that

 int& a = 5; 

also not legal in standard C ++.

In general, however, it is legal to initialize a const reference with any expression that can be converted to the correct type (including the use of a conditional operator). And it is not legal to initialize a link with a value of the correct type, which the conditional operator gives under certain conditions.

+5
source

The ternary operator does not expand to the if-else (not in accordance with the language, the implementation can generate equivalent binary files, but at the language level they are different). Thus, the following code is valid:

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

The original example in the question depends on the Microsoft extension, which (incorrectly) allows you to bind a non-constant link to the rvalue expression.

+4
source

The conditional operator is an expression, not an expression. It is perfectly normal to initialize such a link. This is a bit like initializing a link by calling a function.

Note that your link must be const if you bind it to temporary ones (a rule that MSVC ++ foolishly ignores).

+3
source

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

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

Change the line to:

 const int& a = isfive ? 5 : 4; 

does a compilation.

+2
source

This not normal

 int& a = isfive ? 5 : 4; 

unless you declare the link "a" as const .

+1
source

This is an operator, part of an expression, not an operator. And you cannot leave the link uninitialized even for a short time; -)

0
source

Source: https://habr.com/ru/post/907978/


All Articles