Why does splint suggest that { 0 } doesn't really initialize all elements to zero in C: Initializer does not define all elements of a declared array

153 views Asked by At

In this piece of code (the whole file contains only one line):

char buffer[256] = { 0 };

Checked with Splint, I got the following hint:

foo.c(1,20): Initializer block for buffer has 1 element, but declared as char
                [256]: 0
  Initializer does not define all elements of a declared array. (Use
  -initallelements to inhibit warning)

Initializer does not define all elements of a declared array. This is puzzling: I read some SO answers, but all of them claims that { 0 } does initialize all elements to zero.


Splint version:

Splint 3.1.1 --- 12 April 2003

Maintainer: [email protected]
Compiled using Microsoft Visual C++ 6.0

Downloaded from Splint.org.

2

There are 2 answers

1
HolyBlackCat On BEST ANSWER

Yes, it does zero all the elements. The general rule is that if you provide less initializers than there are elements, the remaining elements are zeroed. (So e.g. char buffer[256] = {1}; will set only the first element to 1, and the rest to 0.)

The warning doesn't say that remaining elements are uninitialized, it says you didn't provide initializers for them. This warning doesn't make sense in this specific case (= {0} is a common pattern to zero an array), but in general it could be useful (e.g. it would warn about int arr[4] = {1,2,3};).

7
artm On

For char array like that, the most common (and safe) way seems to be:

char buffer[256] = "";

It may be initialised using empty {} just like other struct types:

char buffer[256] = {};  // not working in C, only work for C++

Using {0} seems to be more C++ way to initialise struct type.