为什么"初始化字符串的字符数组太长"在编译C和罚款;不是C ++? [英] Why "initializer-string for array of chars is too long" compiles fine in C & not in C++?

查看:4020
本文介绍了为什么"初始化字符串的字符数组太长"在编译C和罚款;不是C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的程序用C编译罚款与警告,但未能在编译的C ++。为什么?原因是什么?

Following program compiles fine in C with warnings but fails in compilation in C++. Why? What is the reason?

#include <stdio.h>
int main(void)
{
    char a[5]="Hello";
    a[0]='y';
    puts(a);
    for(int i=0;i<5;i++)
        printf("%c",a[i]);
    return 0;
}

警告:

Warning:[Error] initializer-string for array of chars is too long [-fpermissive] enabled by default

但如果程序保存在C ++程序,然后C ++编译器提供了以下错误:

But if the program is saved C++ program then C++ compiler gives following error:

[Error] initializer-string for array of chars is too long [-fpermissive]

我使用GCC 4.8.1编译器。

I am using GCC 4.8.1 compiler.

推荐答案

简短的回答:因为C和C ++是不同的规则不同语言

Short answer: Because C and C++ are different languages with different rules.

龙答:在这两种情况下,原因是该阵列是字符串字面太小。字面由五个可见字符,以0终结的结束,所以总大小为6。

Long answer: In both cases the reason is that the array is too small for the string literal. The literal consists of the five visible characters, with a zero terminator on the end, so the total size is 6.

在C,你被允许使用初始化字符串时间太长的数组;多余的字符被忽略:

In C, you're allowed to initialise an array with a string that's too long; extra characters are simply ignored:

C99 6.7.8 / 14:字符类型的数组,可以用字符串文字,可选择在大括号初始化。字符串字面量连续的字符(包括终止空字符,如果有空间,或者如果数组是未知大小的)初始化数组中的元素。

C99 6.7.8/14: 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.

编译有益警告字符串过大,因为这几乎肯定指示错误;但除非你告诉它来治疗警告视为错误就不能拒绝code。

The compiler helpfully warns that the string is too large, since it almost certainly indicates an error; but it can't reject the code unless you tell it to treat warnings as errors.

在C ++中,初始化器不允许将大于该数组:

In C++, the initialiser isn't allowed to be larger than the array:

C ++ 11 8.5.2 / 2:不应当有更多的初始化值多于数组元素

C++11 8.5.2/2: There shall not be more initializers than there are array elements.

因此​​,对于语言,编译器应该给出一个错误。

so, for that language, the compiler should give an error.

在这两种语言,当你想要一个字符数组是一个字符串初始化器大小合适,你可以离开了大小出来,编译器会做正确的事。

In both languages, when you want a character array to be the right size for a string literal initialiser, you can leave the size out and the compiler will do the right thing.

char a[] = "hello";  // size deduced to be 6

这篇关于为什么&QUOT;初始化字符串的字符数组太长&QUOT;在编译C和罚款;不是C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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