Search code examples
c++compilationif-statementvariable-declaration

C++, variable declaration in 'if' expression


What's going on here?

if(int a = Func1())
{
    // Works.
}

if((int a = Func1()))
{
    // Fails to compile.
}

if((int a = Func1())
    && (int b = Func2()))
)
{
    // Do stuff with a and b.
    // This is what I'd really like to be able to do.
}

Section 6.4.3 in the 2003 standard explains how variables declared in a selection statement condition have scope that extends to the end of the substatements controlled by the condition. But I don't see where it says anything about not being able to put parenthesis around the declaration, nor does it say anything about only one declaration per condition.

This limitation is annoying even in cases where only one declaration in the condition is required. Consider this.

bool a = false, b = true;

if(bool x = a || b)
{

}

If I want to enter the 'if'-body scope with x set to false then the declaration needs parenthesis (since the assignment operator has lower precedence than the logical OR), but since parenthesis can't be used it requires declaration of x outside the body, leaking that declaration to a greater scope than is desired. Obviously this example is trivial but a more realistic case would be one where a and b are functions returning values that need to be tested

So is what I want to do non-conformant to the standard, or is my compiler just busting my balls (VS2008)?


Solution

  • As of C++17 what you were trying to do is finally possible:

    if (int a = Func1(), b = Func2(); a && b)
    {
        // Do stuff with a and b.
    }
    

    Note the use of ; of instead of , to separate the declaration and the actual condition.