Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

auto assignment in if clause

Tags:

c++

c++11

c++14

I have code below and it reports "auto is 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 below if fine.

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

The reason behind could be silly buy may I ask why? I am using Visual Studio 2017

like image 991
Bing Lan Avatar asked Dec 14 '17 23:12

Bing Lan


People also ask

Can we use assignment operator in if condition?

Using the assignment operator in conditional expressions frequently indicates programmer error and can result in unexpected behavior. The assignment operator should not be used in the following contexts: if (controlling expression)

How do you declare a variable as auto in C++?

To use the auto keyword, use it instead of a type to declare a variable, and specify an initialization expression. In addition, you can modify the auto keyword by using specifiers and declarators such as const , volatile , pointer ( * ), reference ( & ), and rvalue reference ( && ).


1 Answers

Your first version:

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

is not allowed under any c++ standard, as you can not have declarations in expressions.

§6.4 (from c++11) Selection statements defines what an if statement looks like:

  • if (condition) statement
  • if (condition) statement else statement

Further down condition is defined:

  • expression
  • attribute-specifier-seqopt decl-specifier-seq declarator = initializer-clause
  • attribute-specifier-seqopt decl-specifier-seq declarator braced-init-list

This allows us to write things like

if (auto ret = Foo())

However, in c++17 and forward, the definition changed (and moved to §9.4):

  • if constexpropt (init-statementopt condition) statement
  • if constexpropt (init-statementopt condition) statement else statement

We can now write things like:

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

Which should be useful for your purpose.

like image 63
sp2danny Avatar answered Sep 20 '22 20:09

sp2danny