what is the differences for a value declared in a list surrounding by a curly bracket and no curly bracket

Viewed 57

I'm a beginner in C programming and I can't figure out what the difference is between these two expressions (with and without curly brackets) as follows.

char s1[] = {"The course of true love never did run smooth"};
char s1[] = "The course of true love never did run smooth";

I try to test by using

printf("%c", s1[0]), and 
printf("%s", s1) 

Both giving me same answer.

2 Answers

There is no difference, the braces are optional.

From the standard 6.7.9/14:

An array of character type may be initialized by a character string literal or UTF−8 string literal, optionally enclosed in braces.

In fact when a character array is initialized by a string literal like for example

char s[] = "Hello";

then such an initialization is equivalent to the following

char s[] = { 'H', 'e', 'l', 'l', 'o', '\0' };

That is elements of the string literal form an initializer list.

So you may initialize an array like

char s[] = "Hello";

or like

char s[] = { "Hello" };

to show that elements of the literal form an initializer list.

Pay attention also to that you may initialize scalar objects also like for example

int x = 10;

or

int x = { 10 };
Related