Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ array initialization

Tags:

c++

syntax

is this form of intializing an array to all 0s

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}  
like image 953
Eli Avatar asked Dec 17 '09 09:12

Eli


People also ask

Do arrays need to be initialized in C?

An array may be partially initialized, by providing fewer data items than the size of the array. The remaining array elements will be automatically initialized to zero. If an array is to be completely initialized, the dimension of the array is not required.

Do C arrays initialize to 0?

Initialize Arrays in C/C++ c. The array will be initialized to 0 if we provide the empty initializer list or just specify 0 in the initializer list.


2 Answers

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.

like image 67
AnT Avatar answered Oct 21 '22 14:10

AnT


Note that the '=' is optional in C++11 universal initialization syntax, and it is generally considered better style to write :

char myarray[ARRAY_SIZE] {0} 
like image 44
incises Avatar answered Oct 21 '22 13:10

incises