Automatic assignment in the if condition

I have the code below and it says that "cars are not allowed here"

//GeSettings() returns boost::optional<ValueType> and could be empty

if((auto ret = GetSettings(InputField)) && ShouldWeDoThis())
{
   do something with ret;
}

but changing, as shown below, in the case of a fine.

if(auto ret = GetSettings(InputField))
{
    if(ShouldWeDoThis())
    {
        do something with ret;
    }
}

The reason may be a stupid purchase, may I ask why? I am using Visual Studio 2017

+6
source share
2 answers

As said here in this link

A condition in an if or while expression can be either an expression or a declaration of a single variable (with initialization).

So, if you try this code, you will get an error again.

if((auto ret = GetSettings(InputField)))
{
    if(ShouldWeDoThis())
    {
        do something with ret;
    }
}

Rules for declaring variables in a select statement:

  • can only have one variable declared per expression
  • variable declaration must occur first in the expression and
  • ( )
+5

:

if((auto ret = GetSettings(InputField)) && ShouldWeDoThis())

c++, .

§6.4 ( c++ 11) , if:

  • if ()
  • if ()

:

  • - -- =
  • - -- -INIT-

,

if (auto ret = Foo())

c++ 17 ( §9.4):

  • constexpr (INIT- )
  • constexpr ( -)

, :

if (auto ret=Foo(); ret && Bar())

.

0

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


All Articles