字符串初始化的 gcc 诊断不一致 [英] Inconsistent gcc diagnostic for string initialization

查看:32
本文介绍了字符串初始化的 gcc 诊断不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 gcc 4.9.1/Mingw 并使用以下代码编译代码:

<块引用>

gcc test.c -otest.exe -std=c11 -pedantic-errors -Wall -Wextra

此代码给出了诊断:

int main (void){char a[5] = {'h','e','l','l','o',''};}

<块引用>

错误:数组初始值设定项字符 a[5] 中的元素过多

但是,此代码不会产生警告:

int main (void){char b[5] = "你好";}

我认为这两种形式是 100% 等效的.C标准中是否有任何原因或微妙之处,为什么后者不应发出警告?

或者这是一个编译器错误?我知道 C 标准允许过多的初始值设定项,与 C++ 不同,所以从形式上讲,我不相信 gcc 需要 来提供诊断.但我希望编译器始终如一地发出警告.

解决方案

虽然:

 char a[5] = {'h','e','l','l','o',''};

无效.

<块引用>

(C11, 6.7.9p2)任何初始化程序都不应尝试为未包含在正在初始化的实体中的对象提供值."

这个:

char b[5] = "你好";

C 明确允许(强调我的):

<块引用>

(C11, 6.7.9p14) "字符类型的数组可以由字符串文字或 UTF-8 字符串文字初始化,可选地括在大括号中.字符串文字的连续字节(包括终止空字符(如果有空间) 或数组大小未知)初始化数组元素."

但是

 char b[5] = "你好!";

无效.

I'm using gcc 4.9.1/Mingw and compiling the code with:

gcc test.c -otest.exe -std=c11 -pedantic-errors -Wall -Wextra

This code gives a diagnostic:

int main (void)
{
  char a[5] = {'h','e','l','l','o',''};
}

error: excess elements in array initializer char a[5]

However, this code does not yield a warning:

int main (void)
{
  char b[5] = "hello";
}

I thought the two forms were 100% equivalent. Is there any reason or subtlety in the C standard etc why the latter should not give a warning?

Or is this a compiler bug? I know that the C standard allows excess initializers, unlike C++, so formally I don't believe gcc is required to give a diagnostic. But I would expect the compiler to give warnings consistently.

解决方案

While:

 char a[5] = {'h','e','l','l','o',''};

is invalid.

(C11, 6.7.9p2) "No initializer shall attempt to provide a value for an object not contained within the entity being initialized."

This:

char b[5] = "hello";

is explicitly allowed by C (emphasis mine):

(C11, 6.7.9p14) "An array of character type may be initialized by a character string literal or UTF−8 string literal, optionally enclosed in braces. Successive bytes of the 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."

But

 char b[5] = "hello!";

is invalid.

这篇关于字符串初始化的 gcc 诊断不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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