Reputation: 348
What is the best way to initialize a boolean array in C99?
Maybe I can use this, I think.
bool f[5] = {false,};
Is this really okay?
If there is a better way, please let me know.
Upvotes: 2
Views: 12708
Reputation: 61
This question is old, but still first result on google if you search for "initialize bool array" on Google. The answer the author accepted is plain wrong and works by luck, not design. This fact is worth mentioning as an answer itself.
Bugfinger pointed this out in the comments to the accepted answer.
You can try it yourself by declaring:
bool array[4] = { true}
and check [1], [2] and [3] which are initialized to "0" (false) - which is correct and in the C99 standard. "All array elements that are not initialized explicitly are zero-initialized."
See: https://en.cppreference.com/w/c/language/array_initialization
Upvotes: 4
Reputation: 320421
If you want to initialize your array to "all false"/"all zeros" initial value, you can do
bool f[5] = { false };
or you can do
bool f[5] = { 0 };
Which variant is "the best" is for you to decide. There's no definitively "best" way here. Each one is as good as the other.
Upvotes: 7