c++ - 字符四 [4] = "four";该语句的正确语义是什么?

标签 c++ c arrays initialization string-literals

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

当编译为 C++ 程序时,G++ 报告

xxx.cpp: In function int main():

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

当编译一个 C 程序时,GCC 没有报错。

在我看来,赋值正确地将所有 4 个字节复制到变量中,正如我预期的那样。

所以我的问题归结为......

在 C 中观察到的行为是否正确,或者我是否在某处触及未定义的行为, 还是完全不同?

最佳答案

简短回答:您的代码是有效的 C,但不是有效的 C++。

长答案:

"four" 实际上是 5 个字符长 - 为您添加了一个 \0。在 6.7.8 初始化 部分的第 13 段中,C 标准说:

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 段)中被明确调用:

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 ]

关于c++ - 字符四 [4] = "four";该语句的正确语义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3524053/

相关文章:

c - Flash下载代码到STM32F4单片机;如何删除下载的代码?

Java读取.txt文件到数组

javascript - 如果它是多维数组或对象或两者,如何从 Meteor 集合中获取元素?

javascript - Underscore.js,根据键值删除对象数组中的重复项

c++ - 简单 LinkedList 程序中的析构函数段错误

c++ - 为什么我会在这里出现堆栈溢出?

c++ - 获取 char 的十进制 ascii 值

C++ 预处理器 : Iterate over comma-separated list argument

c - 堆内存 C 中的二维结构数组

c - scanf后修改参数