Инициализация массива C++

эта форма инициализации массива ко всему 0s

char myarray[ARRAY_SIZE] = {0} поддерживаемый всеми компиляторами?,

если так, есть ли подобный синтаксис к другим типам? например,

bool myBoolArray[ARRAY_SIZE] = {false} 
77
задан Sander Rijken 17 December 2009 в 09:25
поделиться

2 ответа

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++.

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 };

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

char* myPtrArray[ARRAY_SIZE] = { 0 };

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 };

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

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.

132
ответ дан 24 November 2019 в 10:55
поделиться

Да, я считаю, что это должно работать, и его также можно применять к другим типам данных.

Однако для массивов классов, если в списке инициализатора меньше элементов, чем элементов в массиве , для остальных элементов используется конструктор по умолчанию. Если для класса не определен конструктор по умолчанию, список инициализаторов должен быть полным, то есть должен быть один инициализатор для каждого элемента в массиве.

0
ответ дан 24 November 2019 в 10:55
поделиться
Другие вопросы по тегам:

Похожие вопросы: