Adding the ()
for a POD instantiation, invokes value initialization in C++03 and later. In C++98 it invoked default initialization. But both reduce to zero initialization for POD types, and for booleans zero is false.
E.g., if S
is a POD struct
, and you have a variable
S o;
then you can zero it by doing
o = S();
No need for unsafe and ugly memset
.
By the way, std::vector<bool>
is a higher level alternative to your raw array of bool
, but due to what's now seen as premature optimization it has a bit odd behavior: it supports an implementation with each boolean value represented by a single bit, and so dereferencing an iterator doesn't give you a reference to a bool
as one might expect from general std::vector
. So a better alternative is e.g. std::vector<My_bool_enum>
, with My_bool_enum
properly defined. Or just std::vector<char>
. ;-)
Regarding
“And why
!boolArray[i]
returnsfalse
in Visual Studio but it returnstrue
in Eclipse?!?”
It's just that Visual C++ chooses efficiency, not initializing where it doesn't have to, while the compiler used in Eclipse (presumably g++) does initialize even though it doesn't have to and isn't requested to do.
I prefer the Visual C++ behavior here for two reasons:
A main idea in C++ is that you don't pay for what you don't use, and the Visual C++ behavior here is in line with that idea.
Zero-initialization can easily give users the false impression that their code works, when in fact it's not portable.