[c++] C++ array initialization

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} 

This question is related to c++ syntax

The answer is


Yes, I believe it should work and it can also be applied to other data types.

For class arrays though, if there are fewer items in the initializer list than elements in the array, the default constructor is used for the remaining elements. If no default constructor is defined for the class, the initializer list must be complete — that is, there must be one initializer for each element in the array.


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}

You can declare the array in C++ in these type of ways. If you know the array size then you should declare the array for: integer: int myArray[array_size]; Double: double myArray[array_size]; Char and string : char myStringArray[array_size]; The difference between char and string is as follows

char myCharArray[6]={'a','b','c','d','e','f'};
char myStringArray[6]="abcdef";

If you don't know the size of array then you should leave the array blank like following.

integer: int myArray[array_size];

Double: double myArray[array_size];