2

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
o o
  • 145
  • 6
  • 1
    There is no difference in the initialization of the array, both ar equivalent. – Some programmer dude Jun 17 '21 at 08:18
  • 3
    seems like a dupe of [Braces around string literal in char array declaration valid? (e.g. char s\[\] = {"Hello World"})](https://stackoverflow.com/questions/10147264/braces-around-string-literal-in-char-array-declaration-valid-e-g-char-s) – underscore_d Jun 17 '21 at 08:30

2 Answers2

1

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.

Lundin
  • 195,001
  • 40
  • 254
  • 396
  • As for the rationale why braces are optionally allowed, I suspect it is because braces can in some cases make it easier to do generic programming with various different initializer lists using macros. I don't have any source for that though. – Lundin Jun 17 '21 at 08:24
1

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 };
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335