8

In the load data part of a program written in C language, I see the initialization of a buffer is done like this:

char buffer[100] = {0, };

But I'm not sure about what values are assigned by this statement. Please share some ideas.

Does this depend on the compiler or is it a language feature?

And what is the point using a comma after that zero, if this statement is equivalent to:

char buffer[100] = {0};

Is it, by any chance, because the coder only want to make sure that the first element is zero, and don't care about the rest?

George
  • 3,384
  • 5
  • 40
  • 64

4 Answers4

12

Does this depend on the compiler or is it a language feature?

The behaviour is specified by the language standard. The current standard (C11 §6.7.9 Initialization / 21, which is at page 141) describes what happens when you supply fewer initializers than elements of an aggregate:

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

So, the elements that are not specified are initialized to \0.

George
  • 3,384
  • 5
  • 40
  • 64
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Ah! in the front of Section 6.7.9 Initialization of [C11](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf), the syntax explicitly support the format of `{0, }` as `{ initializer-list , }`. – George Apr 23 '13 at 13:16
6

The value(s) given (a single 0 in this case) are used, and then all other members are filled with zeros.

Had you said char buffer[100] = {1, };, the array would contain a 1 and 99 zeros.

RichieHindle
  • 272,464
  • 47
  • 358
  • 399
4

buffer[100] = {literal, } initializes the first element to the literal value and the rest to 0.On the other hand buffer[100] = {0} initializes all the elements to 0.Your code is equivalent to buffer[100] = {0} as both initialize all elementts to 0.RichieHindle's buffer[100] = {1, } illustrates the whole point.

Rüppell's Vulture
  • 3,583
  • 7
  • 35
  • 49
1

Initializers for an array of a given size are assigned to array members on a one-to-one basis. If there are too few initializers for all members, the remaining members are initialized to 0. Listing too many initializers for a given size array is an error.

evilruff
  • 3,947
  • 1
  • 15
  • 27