int main(void)
{
char four[4] = "four";
return 0;
}
When compiled as a C++ program, G++ reports
xxx.cpp: In function int main():
xxx.cpp:3: error: initializer-string for array of chars is too long
When compiled a a C program, GCC reports no error.
It appears to me, that the assignment is correctly copying all 4 bytes into the variable, as I expected.
So my question boils down to…..
Is the observed behavior in C correct or am I touching an undefined behavior somewhere,
or is it something else altogether?
Short answer: your code is valid C, but not valid C++.
Long Aswer:
"four"is actually 5 characters long – there is a\0added there for you. In section 6.7.8 Initialization, paragraph 13, the C standard says:So the
\0is 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):