#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?
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).
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