Initialization

Using Initializer List
To initialize an array in C/C++ with the same value, the naive way is to provide an initializer list like,
int arr[5] = { 1, 1, 1, 1, 1};
 
// or don't specify the size
int arr[] = { 1, 1, 1, 1, 1 };
The array will be initialized to 0 if we provide the empty initializer list or just specify 0 in the initializer list.
int arr[5] = {};    // results in [0, 0, 0, 0, 0]
int arr[5] = { 0 }; // results in [0, 0, 0, 0,0]



Using Designated Initializers
With GCC compilers, we can use designated initializers. To initialize a range of elements to the same value, we can write
[first ... last] = value.

int arr[5] = {[0 ... 4] = 1};
 
// or don't specify the size
int arr[] = {[0 ... 4] = 1};


Posted on by