1

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: splint-bug@splint.org
Compiled using Microsoft Visual C++ 6.0

Downloaded from Splint.org.

user26742873
  • 919
  • 6
  • 21

2 Answers2

3

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};).

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
0

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.

artm
  • 17,291
  • 6
  • 38
  • 54
  • 3
    `= {}` doesn't work in C, it's a C++ thing. Otherwise we wouldn't be using `= {0}`. – HolyBlackCat Aug 09 '20 at 07:27
  • Initializing with `""` is great! I didn't think of that. – user26742873 Aug 09 '20 at 07:28
  • 1
    @Ayoama initializing with `""` doesn't set to zero all the array but just the first element: that is the nul char terminating an empty string. – Roberto Caboni Aug 09 '20 at 08:08
  • 1
    @RobertoCaboni are you sure? See this https://stackoverflow.com/questions/18688971/c-char-array-initialization – artm Aug 09 '20 at 08:12
  • 1
    @artm I used to be.. :) Probably I had to deal too much with c89 stuff. I'll verify it. – Roberto Caboni Aug 09 '20 at 08:29
  • 2
    `={0}` is common enough in C – ikegami Aug 09 '20 at 21:59
  • 1
    Not sure I fully understand this answer. 1) Why C++ code? As far as I can see the Q has never had a C++ tag. 2) Why should it be more "safe"? 3) Do you a reference for the "most common" claim? To me it would depend on the use of `buffer`. If `buffer` was to be used as a string, I would initialize with `""` but if `buffer` was be used for other things I would initialize with `{0}`. – Support Ukraine Aug 10 '20 at 10:19