0

I have some input flags in a C++ program, they all start out false. I thought it might be nice, if I could initialize all of them to false. So I tried:

bool flagA, flagB, flagH = false;

but the flags did not get set properly, when I tried this. flagA evidently was initialized as true? Setting the flags explicitly works.

bool flagA = false;
bool flagB = false;
bool flagH = false;

I am using g++, and I do not get compiler errors or warnings. I know the program is misbehaving because flagA when set true sends program output to the local printer. Just wondering.

j0h
  • 1,675
  • 6
  • 27
  • 50

1 Answers1

5

When compiler sees bool flagA, flagB, flagH = false; he translates is as

User needs three bool values, named flagA, flagB and flagC. Oh, and flagC shall be initialized to false.

It's just shorter writing for

bool flagA;
bool flagB;
bool flagC = false;

And since they are local scope variables (probably), they are not guaranteed to be initialized with default value.

Zereges
  • 5,139
  • 1
  • 25
  • 49
  • In C++, bools are objects right? So, won't the default contructor kick in and initialize to 0? – nirvanaswap Aug 11 '17 at 16:54
  • @nirvanaswap In C++, `bool` is not object and no default construction happens. But you can force default initialization using `bool flagA{};`. – Zereges Aug 12 '17 at 16:49