-1

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?

Dasha
  • 27
  • 3
  • 1
    You can try `memset()` [Here for detail](https://stackoverflow.com/questions/9146395/reset-c-int-array-to-zero-the-fastest-way/9146410) – Peter Lee Dec 09 '21 at 01:20
  • 2
    Anything preventing you from benchmarking alternative approaches and getting useful metrics for your hardware? – Sam Varshavchik Dec 09 '21 at 01:28
  • 2
    Tactical note: You rarely need fastest. Stopping at fast enough typically has a shorter development cycle. – user4581301 Dec 09 '21 at 01:33
  • If you can't measure the impact of zero-initialization versus no initialization, then your program does not need optimization in this area. Some code profiling and instrumentation will help you uncover the main performance hogs. I strongly suspect this isn't one of them. – paddy Dec 09 '21 at 01:48
  • btw CA is const – Dasha Dec 09 '21 at 01:56
  • `const` isn't necessarily the same as a compile time constant. `const` is a promise that a value will not be changed after it's initialized, but the value provided at initialization need not be `const` or a compile-time constant. If you have a class member variable, each instance of the class could have a different value that is determined at runtime. A `const` function parameter could be provided with different values on every invocation. It's easy to fall into little traps by overestimating the constant-ness of a `const` variable. – user4581301 Dec 09 '21 at 02:08

2 Answers2

1

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

This will zero-initialize all members of the array.

0

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • 2
    [Details on the different types of Initialization](https://en.cppreference.com/w/cpp/language/initialization) – user4581301 Dec 09 '21 at 01:29