I read this question and its answer in a book. But I didn’t understand the book’s justification.
Will the following code compile?
int main()
{
char str[5] = "fast enough";
return 0;
}
And the answer was:
Yes.The compiler never detects the
error if bounds of an array are
exceeded.
I couldn’t get it.
Can anybody please explain this?
In the C++ standard, 8.5.2/2 Character arrays says:
In the C99 standard, 6.7.8/2 Initialization says:
C90 6.5.7 Initializers says similar.
However, note that for C (both C90 and C99) the ‘\0’ terminating character will be put in the array if there is room. It’s not an error if the terminator will not fit (C99 6.7.8/14: “Successive characters of the character 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”).
On the other hand, the C++ standard has an example that indicates an error should be diagnosed if there’s not room for the terminating character.
in either case, this should be diagnosed as an error in all compilers:
Maybe pre-ANSI compilers weren’t so strict, but any reasonably modern compiler should diagnose this.