Why does gcc allow char array initialization with string literal larger than array?

Initializing a char array with a string literal that is larger than it is fine in C, but wrong in C++. That explains the difference in behavior between gcc and VC++.

You would get no error if you compiled the same as a C file with VC++. And you would get an error if you compiled it as a C++ file with g++.

The C standard says:

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' };

(Section 6.7.9 of the C11 draft standard, actual wording in final standard might be different.)

This means that it’s perfectly correct to drop the termination character if the array doesn’t have room for it. It’s maybe unexpected, but it’s exactly how the language is supposed to work, and a (at least to me) well-known feature.

On the contrary, the C++ standard says:

There shall not be more initializers than there are array elements.

Example:

 char cv[4] = "asdf"; // error

is ill-formed since there is no space for the implied trailing ‘\0’.

(8.5.2 of the C++ 2011 draft n3242.)

Leave a Comment