Is there a better way to initialize an array?

Given an array of arrays with a 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

+5
source share
5 answers
bool map[256] = { false };

edit: for a reference to the standard regarding why this is legal, see the answers below.

+18
source
bool map[256] = {false};

(C ++ also allows bool map[256] = {};. The above works in C.)

This will set the remaining 255 members map[0]to falseand “default initialize” (C ++ 98 §8.5.1 / 7: “If there are fewer initializers in the list than there are members in the aggregate, each element that is not explicitly initialized should be initialized by default” ; C99 §6.7.8 / 21).

bool "default-initialize" (bool)0, .. false (++ 98 §8.5/5; C99 §6.7.8/10).

, , true.

+15

:

bool map[256] = { 0 };

:

bool map[256] = {};

.

"0", "false"? , , 0, . 1 255 "0" (, , false), 0, "0". "0" , .

, 8.5.1/7 ( , ), 8.5/5 ( a bool 0, bool).

+7
source

If you have no reason to do this, the best option is probably to use a vector:

std::vector<bool> map(256, false);

vector<bool>, however, is a specialization that is different from what you expect. Depending on the situation, you may prefer:

std::vector<char> map(256, false);
+3
source

In C ++, X = {0} is an idiomatic universal null initializer. This was a function ported from C.

bool map[256] = { 0 };
+2
source

All Articles