Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expected to see "initializer-string for array of chars is too long" warning [duplicate]

Tags:

c

gcc

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.

like image 477
R Sahu Avatar asked Mar 15 '23 15:03

R Sahu


1 Answers

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.

like image 181
kaylum Avatar answered Apr 06 '23 22:04

kaylum