Home > Back-end >  Initializing an Array in C : the fastest way?
Initializing an Array in C : the fastest way?

Time:12-09

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?

CodePudding user response:

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.

CodePudding user response:

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

This will zero-initialize all members of the array.

  • Related