烧焦4 [4] ="四英寸;什么是这种说法正确的语义? [英] char four[4] = "four"; What are the correct semantics for this statement?

查看:97
本文介绍了烧焦4 [4] ="四英寸;什么是这种说法正确的语义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main(void)
{
    char four[4] = "four";
    return 0;
}

在为C ++程序编译,G ++报道

When compiled as a C++ program, G++ reports

xxx.cpp:在函数int main()中:

xxx.cpp:3:错误:初始化字符串的字符数组太长

在编译一个C语言程序,GCC报告没有错误。

When compiled a a C program, GCC reports no error.

在我看来,该分配正确复制所有4个字节到变量,如我所料。

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

是在C中观察到的行为正确的还是我接触的地方不确定的行为,
抑或是别的东西完全?

推荐答案

简短的回答:你的code是合法的C,但不是有效的C ++

Short answer: your code is valid C, but not valid C++.

龙Aswer:

四有实际上是5个字符长 - 有一个 \\ 0 添加为您服务。在第 6.7.8初始化,第13段,C标准说:

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

所以 \\ 0 只是忽略了你的程序时,它为C. C ++是区别对待它编译。事实上,这种特殊情况下被调出的明确在C ++规范的(见 8.5.2字符数组,第2段):

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


  
  

是病态的,因为对于没有空间隐含尾随'\\ 0'。 - 结束例如的]

这篇关于烧焦4 [4] ="四英寸;什么是这种说法正确的语义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆