Initializing an Array in C++ : the fastest way?

1.2k Views Asked by At

What is the fastest way to initialize with zeros an array of int in C++?

int plus_number[CA - 1];
for (int & i : plus_number) {
    i = 0;
}

or

int plus_number[CA - 1] = {0};

or maybe there is another way?

2

There are 2 best solutions below

1
On

Fastest way to initialise an array is to default initialise it. In case of trivially default initialisable element type (and non-static storage duration), this leaves the elements with an indeterminate value.

You can use value initialisation instead if you want all elements to be zero. This may be marginally slower than default initialisation. Both of your suggestions are potentially as fast as value initialisation.

0
On

You can simply use int plus_number[CA - 1]{};

This will zero-initialize all members of the array.