char four[4] = “four”; What are the correct semantics for this statement?

徘徊边缘 提交于 2019-12-01 16:37:20

问题


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?


回答1:


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 ]




回答2:


The string "four" actually contains five bytes: the four letters plus a zero byte (\0) as a string terminator. It's been a while since I've written C or C++, but I would guess the C compiler is silently ignoring it for whatever reason.




回答3:


Better would be

char four[] = "four";



回答4:


What you're seeing is a difference between C and C++. C allows you to have extra initializers, which are ignored. C++ prohibits this -- if you specify a size for a string (or array) it must be large enough to accommodate all the initializers (including the NUL terminator, in the case of a string), or the code is ill-formed (standardese for "it's not allowed -- expect the compiler to reject it").



来源:https://stackoverflow.com/questions/3524053/char-four4-four-what-are-the-correct-semantics-for-this-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!