Aren't Boolean variables always false by default?

Talking about primitive built-in data types (bool, char, wchar_t, short, int, long, float, double, long double), according to C++ standard, only global variables get a default value of zero if they are not explicitly initialized.

For local variables it's not required for the complier to clean up the content of the memory they are assigned to. A local variable -- if not explicitly initialized -- will contain an arbitrary value.


Yes, you should always initialize your variables. Until you intimately learn the times when it is and isn't necessary to do so explicitly, you should do it all the time, no matter what. And by then...well...why stop a good habit?

To initialize a bool to false it's sufficient to default construct it:

struct X
{
  bool b;
  X() : b() {}
};

Only global variables are assigned 0 (false) by default. Any local variables are given a non-zero garbage value, which would evaluate to true in a boolean variable.

Tags:

C++

Syntax