C++ 使用 {0}、{0、} 初始化数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5591492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:28:06  来源:igfitidea点击:

Array initialization with {0}, {0,}?

c++carraysinitialization

提问by eugene

Say I want to initialize myArray

说我想初始化 myArray

char myArray[MAX] = {0};  
char myArray[MAX] = {0,};  
char myArray[MAX]; memset(myArray, 0, MAX);  

Are they all equal or any preferred over another?

他们都是平等的还是比另一个更受欢迎?

Thank you

谢谢

采纳答案by Sylvain Defresne

They are equivalent regarding the generated code (at least in optimised builds) because when an array is initialised with {0}syntax, all values that are not explicitly specified are implicitly initialised with 0, and the compiler will know enough to insert a call to memset.

它们在生成的代码方面是等效的(至少在优化的构建中),因为当使用{0}语法初始化数组时,所有未显式指定的值都隐式初始化为 0,并且编译器将足够了解插入对memset.

The only difference is thus stylistic. The choice will depend on the coding standard you use, or your personal preferences.

因此,唯一的区别是风格。选择将取决于您使用的编码标准或您的个人偏好。

回答by user541686

Actually, I personally recommend:

其实我个人推荐:

char myArray[MAX] = {};

They all do the same thing, but I like this one better; it's the most succinct. =D

他们都做同样的事情,但我更喜欢这个;这是最简洁的。=D

By the way, do notethat char myArray[MAX] = {1};does notinitialize all values to 1! It only initializes the first value to 1, and the rest to zero. Because of this, I recommend you don't write char myArray[MAX] = {0};as it's a little bit misleading for some people, even though it works correctly.

顺便说一句,做笔记char myArray[MAX] = {1};不会初始化所有的值比1!它只将第一个值初始化为 1,其余的值初始化为零。正因为如此,我建议你不要写,char myArray[MAX] = {0};因为它对某些人来说有点误导,即使它工作正常。

回答by Nawaz

I think the first solution is best.

我认为第一个解决方案是最好的。

char myArray[MAX] = {0};  //best of all

回答by Jhaliya

Either can be used

都可以用

But I feel the below more understandable and readable ..

但我觉得下面更容易理解和可读..

  char myArray[MAX]; 
  memset(myArray, 0, MAX);

回答by iammilind

Assuming that you always want to initialize with 0.

假设你总是想用 0 初始化。

--> Your first way and 2nd way are same. I prefer 1st.

--> 你的第一种方式和第二种方式是一样的。我更喜欢第一个。

--> Third way of memset()should be used when you want to assign 0s other than initialization.

--> 第三种方式memset()应该是当你想给0赋值而不是初始化的时候。

--> If this array is expected to initialized only once, then you can put statickeyword ahead of it, so that compiler will do the job for you (no runtime overhead)

--> 如果这个数组只需要初始化一次,那么你可以把static关键字放在它前面,这样编译器就会为你做这个工作(没有运行时开销)

回答by Bogdan Ruzhitskiy

You can use also bzero fn (write zero-valued bytes)

您也可以使用 bzero fn(写入零值字节)

#include <strings.h>
void bzero(void *s, size_t n)

http://linux.die.net/man/3/bzero

http://linux.die.net/man/3/bzero