Search code examples
arraysccharinitializationstring-literals

No warning when char array initializer too long by 1


When I try to compile the following:

int main() {
    char a[4] = "1234";  // This string is length 5, no warning
    char b[4] = "12345"; // This string is length 6, produces a warning
}

I get a warning about "initializer-string for char array is too long" or some such only for the second line. does anyone know if this is intentional? Why would the first not produce a warning? I tried both with gcc and clang.


Solution

  • In C opposite to C++ you may initialize a character array with a fixed size with a string literal when the terminating zero character '\0' of the string literal is not stored in the initialized array. In this case the array will not contain a string.

    From the C Standard (6.7.9 Initialization_

    14 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.

    So in this declaration

    char a[4] = "1234";
    

    there is no room in the character array for the terminating zero character '\0' of the string literal.

    As for this declaration

    char b[4] = "12345";
    

    then it breaks the requirement that

    2 No initializer shall attempt to provide a value for an object not contained within the entity being initialized.

    because there is used the initializer '5' (that is not the terminating zero character) for a character not contained in the array b.

    A C++ compiler will issue an error for the both declarations.