简体   繁体   English

在 c99 中初始化布尔数组的方法

[英]way to initialize a boolean array in c99

What is the best way to initialize a boolean array in C99?在 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.如果有更好的方法,请告诉我。

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.每一个都和另一个一样好。

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. Bugfinger 在对已接受答案的评论中指出了这一点。

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.您可以通过声明自己尝试: bool array[4] = { true}并检查初始化为“0”(false)的 [1]、[2] 和 [3] - 这是正确的并且符合 C99 标准。 "All array elements that are not initialized explicitly are zero-initialized." “所有未显式初始化的数组元素都是零初始化的。”

See: https://en.cppreference.com/w/c/language/array_initialization请参阅: https : //en.cppreference.com/w/c/language/array_initialization

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM