Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the initialization using buffer[100] = {0, } work in C language?

Tags:

c

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?

like image 396
George Avatar asked Apr 22 '13 07:04

George


People also ask

How do you initialize a char array to 0?

char ZEROARRAY[1024] = {0}; The compiler would fill the unwritten entries with zeros. Alternatively you could use memset to initialize the array at program startup: memset(ZEROARRAY, 0, 1024);

How is an array initialized in c language?

The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.

What are buffers for in C?

C language's use of a buffer C uses a buffer to output or input variables. The buffer stores the variable that is supposed to be taken in (input) or sent out (output) of the program. A buffer needs to be cleared before the next input is taken in.


1 Answers

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.

like image 79
David Heffernan Avatar answered Sep 28 '22 08:09

David Heffernan