4

I expected to see "initializer-string for array of chars is too long" warning for both of the variables in the following program using gcc.

Program:

int main()
{
   char str1[4]="1234";
   char str2[3]="1234";

   (void)str1; // Remove unused variable warning.
   (void)str2; // Remove unused variable warning.
   return 0;
}

However, I got a warning only for str2.

Since

char str1[4]="1234";

is equivalent to

char str1[4]= {'1', '2', '3', '4', '\0'};

shouldn't we get the same warning for str1 also?

Is this a defect in gcc?

Compiler command:

gcc -Wall -std=c99 soc.c -o soc

gcc version is 4.8.4.

Update

Learned just now that

char str1[4]="1234";

is not equivalent to

char str1[4]= {'1', '2', '3', '4', '\0'};

Update 2

char str1[4]="1234";

is ill-formed in C++11 (Section 8.5.2/2). I didn't think C99 and C++11 would treat them differently.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • 1
    See [No compiler error when fixed size char array is initialized without enough room for null terminator](http://stackoverflow.com/q/20694796/1708801) – Shafik Yaghmour Sep 29 '15 at 09:20

1 Answers1

7

Section 6.7.9 of the C standard reads:

  1. An array of character type may be initialized by a character string literal or UTF −8 string literal, optionally enclosed in braces. Successive bytes of the 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.

...

  1. EXAMPLE 8

    The declaration

    char s[] = "abc", t[3] = "abc";
    

    defines ‘‘plain’’ char array objects s and t whose elements are initialized with character string literals. This declaration is identical to

    char s[] = { 'a', 'b', 'c', '\0' }, t[] = { 'a', 'b', 'c' };
    

(Emphasis mine).

That is, the terminating null character is not added if it does not fit into the fixed known size array.

kaylum
  • 13,833
  • 2
  • 22
  • 31