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.
Section 6.7.9 of the C standard reads:
- 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.
...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With