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
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)
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 ( && ).
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.
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