Question

I need to create a bool array with an unknown length passed by parameter. So, I have the following code:

void foo (int size) {

    bool *boolArray = new bool[size];

    for (int i = 0; i < size; i++) {

            if (!boolArray[i]) {

                cout << boolArray[i];

            }
    }
}

I thought that a boolean array was initializing with false values...

Then, if I run that code in Eclipse (on Ubuntu), it works fine for me, the function prints all the values because !boolArray[i] return true (but the values are not false values, they are garbage values). If I run it in Visual Studio, the values are garbage values too, but the function does not print any value (because !boolArray[i] returns false). Why the array values are not false values by default?!? And why !boolArray[i] returns false in Visual Studio but it returns true in Eclipse?!?

I read this question: Set default value of dynamic array, so if I change the code like the following, it works fine for me too (in Eclipse and in Visual Studio)! But I have no idea why.

void foo (int size) {

    bool *boolArray = new bool[size]();

    for (int i = 0; i < size; i++) {

            if (!boolArray[i]) {

                cout << boolArray[i];

            }      
    }
}

Sorry for my bad English!

Thanks in advance!

Was it helpful?

Solution

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] returns false in Visual Studio but it returns true 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top