Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading