Why does "if (char a = f())" compile whereas "if ((char a = f()))" does not?

Viewed 103
#include <iostream>

char f()
{
    return 0;
}

int main()
{
    // Compiles
    if (char a = f())
        std::cout << a;
        
    // Does not compile (causes a compilation error)
    // if ((char a = f()))
    //     std::cout << a;

    return 0;
}

One can declare a local variable and assign a value to it inside an if statement as such:

if (char a = f())

However, adding an additional pair of parentheses, leading to if ((char a = f())), causes the following compilation error:

error: expected primary-expression before ‘char’

Why is that? What is the difference between both? Why is the additional pair of parentheses not just considered redundant?

1 Answers

To put it simply, C++ syntax allows the condition inside an if statement to be either an expression or a declaration.

So, char a = f() is a declaration (of the variable named a).

But (char a = f()) is not a declaration (and is also not an expression convertible to bool).

Related