md5
md5

Reputation: 23699

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.

Upvotes: 7

Views: 477

Answers (5)

Matthias
Matthias

Reputation: 3556

There is no difference. You can also see for yourself! That's the most reliable answer you can get. Just use a debugger. Execute the two lines and compare the result. But youshould rename the 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 invoke gdb a.out. In gdb i enter

break 5
run
print s

the last statement is answered by gdb 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 compiler of choice both statements result in the same result.

Upvotes: 2

Lundin
Lundin

Reputation: 213842

In addition to what have 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 of these will result in exactly the same machine code: a 32 byte array filled with all zeroes.

Upvotes: 2

Daniel Fischer
Daniel Fischer

Reputation: 183888

In that case, there's no difference, both initialise all slots of the array to 0. In general, "" works only for char arrays (with or without modifications like 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 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 even "" initialises the complete array.

Upvotes: 10

Péter Török
Péter Török

Reputation: 116266

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

Upvotes: 2

ouah
ouah

Reputation: 145839

No there is no difference between both declarations:

char bla[32] = {0};

and

char bla[32] = "";

See the relevant paragraph of the C Standard (emphasis mine):

(C99, 6.7.8p21) "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."

Upvotes: 18

Related Questions