Hello all,
Given an array map with size of 256, what is the best way to initialize it so that each element is false?
bool map[256];
for (int i=0; i<256; i++)
{
map[i] = false;
}
Thank you
Hello all,
Given an array map with size of 256, what is the best way to initialize it so that each element is false?
bool map[256];
for (int i=0; i<256; i++)
{
map[i] = false;
}
Thank you
bool map[256] = {false};
(C++ also allows bool map[256] = {};
. The above works in C too.)
This will set map[0]
to false
, and "default-initialize" the rest of 255 members (C++98 §8.5.1/7: "If there are fewer initializers in the list than there are members in the aggregate, then each member not explicitly initialized shall be default-initialized"; C99 §6.7.8/21).
For bool
, "default-initialize" means set to (bool)0
, i.e. false
(C++98 §8.5/5; C99 §6.7.8/10).
Note that this method doesn't work if you want to initialize to true
.
bool map[256] = { false };
edit: for a reference to the standard as to why this is legal, see the answers below.
Like this:
bool map[256] = { 0 };
Some would say this:
bool map[256] = {};
But to me that just looks a little weird.
Why use "0" rather than "false"? It's not a big deal, but I do it because the array initializer is in effect padded out to the size of the array with 0, not with copies of the first element. Since the initialization of elements 1 through 255 is defined in terms of the value "0" (which of course converts to false
), I see no harm in element 0 being initialized with "0" too. Having a "0" at the end of a too-short initializer list for scalar types reminds me of what's really going on.
Specifically, the standard defines this at 8.5.1/7 (initializer list shorter than array), and 8.5/5 (value-initializing a bool
is equivalent to initializing it with the value 0 converted to bool
).
In C++, X = { 0 } is an idiomatic universal zero-initializer. This was a feature carried forward from C.
bool map[256] = { 0 };
Absent a reason to do otherwise, the best choice is probably to use a vector:
std::vector<bool> map(256, false);
vector<bool>
, however, is a specialization that's rather different from what you might expect. Depending on the situation, you might prefer:
std::vector<char> map(256, false);