What is the difference between {0} and ""?

I would like to know if there is a difference between:

char s[32] = ""; 

and

 char s[32] = {0}; 

Thanks.

+7
source share
5 answers

There is no difference between both declarations:

 char bla[32] = {0}; and char bla[32] = ""; 

See the relevant paragraph of standard C (shock):

(C99, 6.7.8p21) "If there are less initializers in the list enclosed in curly brackets than in the element or elements of the population, or fewer characters in the string literal , an array with a known size is used to initialize than there are elements in the array, the remainder of the aggregate "must be implicitly initialized to the same as objects with static storage duration."

+18
source

In this case, there is no difference, both initialize all slots of the array to 0. In general, "" only works for char arrays (with or without modifications, for example, const or unsigned ), but {0} works for arrays of all numeric types.

In section 6.7.9 of the standard (n1570), point 21 reads

If the list enclosed in curly brackets contains fewer initializers than elements or elements of the population or fewer characters in the string literal used to initialize an array of known sizes than there are elements in the array, the rest of the population must be initialized implicitly in the same way as objects having a static storage duration.

therefore, even "" initializes the full array.

+10
source

The result of both expressions is the same: an empty string. However, the first is more explicit, therefore more readable.

+2
source

There is no difference. You can also see for yourself! This is the most reliable answer you can get. Just use a debugger. Follow the two lines and compare the result. But you have to rename arrays. I use gcc / gdb and compile the following code

 int main(int argc, char* argv[]) { char s[5] = {0}; char t[5] = ""; return 0; } 

via gcc -g test.c and then call gdb a.out. In gdb enter

 break 5 run print s 

gdb answers the last statement with the following output:

 $1 = "\000\000\000\000" 

i continue and enter "print t" and get accordingly

 $2 = "\000\000\000\000" 

which tells me that with my selection compiler, both statements produce the same result.

+2
source

In addition to what has already been said:

 char s[32] = ""; 

=

 char s[32] = {'\0'}; 

=

 char s[32] = {0}; 

=

 char s[32] = {0, 0, 0, /* ...32 zeroes here*/ ,0 }; 

All this will lead to the exact same machine codes: an array of 32 bytes filled with all zeros.

+2
source

All Articles