Braces around string literal in char array declaration valid? (e.g. char s[] = {“Hello World”})

It’s allowed because the standard says so: C99 section 6.7.8, §14:

An array of character type may be initialized by a character string literal, optionally
enclosed in braces. Successive characters of the character string literal (including the
terminating null character if there is room or if the array is of unknown size) initialize the
elements of the array.

What this means is that both

char s[] = { "Hello World" };

and

char s[] = "Hello World";

are nothing more than syntactic sugar for

char s[] = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', 0 };

On a related note (same section, §11), C also allows braces around scalar initializers like

int foo = { 42 };

which, incidentally, fits nicely with the syntax for compound literals

(int){ 42 }

Leave a Comment