Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++14

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

like image 250
Ramanewbie Avatar asked Oct 27 '25 22:10

Ramanewbie


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

like image 50
heap underrun Avatar answered Oct 29 '25 11:10

heap underrun