int main(void)
{
char four[4] = \"four\";
return 0;
}
When compiled as a C++ program, G++ reports
xxx.cpp: In function int
Short answer: your code is valid C, but not valid C++.
Long Aswer:
"four"
is actually 5 characters long - there is a \0
added there for you. In section 6.7.8 Initialization, paragraph 13, the C standard says:
An array of character type may be initialized by a character string literal, optionally enclosed in braces. 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.
So the \0
is just ignored in your program when it is compiled as C. C++ is treating it differently. In fact, this particular case is called out explicitly in the C++ spec (Section 8.5.2 Character arrays, paragraph 2):
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’
. — end example ]