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

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Ramanewbie
  • 232
  • 1
  • 7
  • However, `char a; if ((a = f()))` will compile. :) – Seva Alekseyev Jun 23 '22 at 18:54
  • Different scope on `a` though. – user4581301 Jun 23 '22 at 19:00
  • To have the same scope, and a parenthesized expression, try either `if (char a = (f()))` or `if (char a; (a = f()))` – Ben Voigt Jun 23 '22 at 19:26
  • @BenVoigt My intent was to be able to do something like `if ( !(char a = f()) )`, which your second suggestion allows (`if ( char a; !(a = f()) )`), but it is not available in C++14. – Ramanewbie Jun 23 '22 at 20:30
  • @Ramanewbie: That particular code can be handled by swapping the controlled-block of `if` with the controlled-block of `else`, instead of using `!`. In particular, accessing `a` within the controlled-block of `if (!a)` is pretty useless.... `a` must be zero or you wouldn't enter the `if` at all. – Ben Voigt Jun 23 '22 at 21:05
  • @BenVoigt "accessing `a` within the controlled-block of `if (!a)` is pretty useless" > Yes. I should have said instead that my intent was to do something like `if ( (char a = f()) > 0 )`. Then it could have been useful to access `a` within the controlled-block. "That particular code can be handled by swapping the controlled-block of `if` with the controlled-block of `else`" > That only stands if there is an `else`. – Ramanewbie Jun 23 '22 at 21:42

1 Answers1

3

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

heap underrun
  • 1,846
  • 1
  • 18
  • 22