C++ 数组初始化

2021-12-29 00:00:00 syntax c++

是将数组初始化为全 0 的这种形式

is this form of intializing an array to all 0s

char myarray[ARRAY_SIZE] = {0} 所有编译器都支持吗?,

char myarray[ARRAY_SIZE] = {0} supported by all compilers? ,

如果是,是否有与其他类型类似的语法?例如

if so, is there similar syntax to other types? for example

bool myBoolArray[ARRAY_SIZE] = {false} 

推荐答案

是的,所有 C++ 编译器都支持这种形式的初始化.它是 C++ 语言的一部分.实际上,它是从 C 语言来到 C++ 的一个习语.在 C 语言中 = { 0 } 是惯用的通用零初始化器.这也是几乎在 C++ 中的情况.

Yes, this form of initialization is supported by all C++ compilers. It is a part of C++ language. In fact, it is an idiom that came to C++ from C language. In C language = { 0 } is an idiomatic universal zero-initializer. This is also almost the case in C++.

因为这个初始化器是通用的,对于 bool 数组,你真的不需要不同的语法".0 也可以作为 bool 类型的初始化器,所以

Since this initalizer is universal, for bool array you don't really need a different "syntax". 0 works as an initializer for bool type as well, so

bool myBoolArray[ARRAY_SIZE] = { 0 };

保证用 false 初始化整个数组.还有

is guaranteed to initialize the entire array with false. As well as

char* myPtrArray[ARRAY_SIZE] = { 0 };

保证用 char * 类型的空指针初始化整个数组.

in guaranteed to initialize the whole array with null-pointers of type char *.

如果你认为它提高了可读性,你当然可以使用

If you believe it improves readability, you can certainly use

bool myBoolArray[ARRAY_SIZE] = { false };
char* myPtrArray[ARRAY_SIZE] = { nullptr };

但重点是 = { 0 } 变体给你完全相同的结果.

but the point is that = { 0 } variant gives you exactly the same result.

然而,在 C++ 中,= { 0 } 可能不适用于所有类型,例如枚举类型,它不能用整数 0 初始化.但是 C++ 支持更短的形式

However, in C++ = { 0 } might not work for all types, like enum types, for example, which cannot be initialized with integral 0. But C++ supports the shorter form

T myArray[ARRAY_SIZE] = {};

即只是一对空的 {}.这将默认初始化任何类型的数组(假设元素允许默认初始化),这意味着对于基本(标量)类型,整个数组将被正确初始化为零.

i.e. just an empty pair of {}. This will default-initialize an array of any type (assuming the elements allow default initialization), which means that for basic (scalar) types the entire array will be properly zero-initialized.

相关文章