Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

c - Inconsistent gcc diagnostic for string initialization

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...