Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct and simplest syntactical way to initialise an array to 0 [duplicate]

Tags:

c++

arrays

I am trying to find out the correct way to initialise an array to all zeros (i.e. as if you have done a memset on the array).

I have found the following methods from various areas in stack overflow (and other sources):

char myArray1[10] = {0};
char myArray2[10] = {0,};
char myArray3[10] = {[0 ... 9] = 0};
char myArray4[10] = {0,0,0,0,0,0,0,0,0,0};

I would prefer the simplest syntax variant... I was using {0}, but I have not found any proof this actually is correct.

like image 232
code_fodder Avatar asked Feb 12 '23 06:02

code_fodder


2 Answers

Missing elements in an array will be initialised to 0. In addition, C++ allows you to leave the uniform initialiser empty. So the following works, is minimal and also the most efficient:

T array[N] = {};

It’s worth noting that this works for any type T which can be either default-constructed or initialised, not just built-in types. For example, the following works, and will print foo five times:

#include <iostream>

struct foo {
    foo() { std::cout << "foo()\n"; }
};

int main() {
    foo arr[5] = {};
}

A more extensive list of the different possibilities was posted by aib some time ago.

like image 53
Konrad Rudolph Avatar answered Feb 15 '23 09:02

Konrad Rudolph


From the C++ specification, "Aggregate initialization" (8.5.1):

If there are fewer initializer-clauses in the list than there are members in the aggregate, then each member not explicitly initialized shall be initialized from an empty initializer list.

So each char not in the initializer list would be initialized to char() that is 0.

In C++11 you can type:

char a[10] = {};
char b[10]{};

Some old compilers (or was it in C) may require you add at least one member:

char a[10] = {0};

Naturally, if the array has static lifetime (global or static variable), then it will be zero initialized if there is not initializer:

char global_array[10];

I find it confusing, so I prefer to add the = {} anyway.

About the trailing comma, it is useful if you do something like:

char a[] = {
  1,
  2,
  3,
};

So that you don't make a special case for the last line and you make copy&paste and diffs easier. In your specific case is just useless:

char a[10] = {0,};

That comma does nothing, and it is ugly, so I wouldn't write it.

like image 23
rodrigo Avatar answered Feb 15 '23 09:02

rodrigo