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
1.1k views
in Technique[技术] by (71.8m points)

c - Why would GCC/Clang accept const qualified object as initializer for object with static storage duration?

As far as I know, the ISO C standard is strict about initializers for object with static storage duration in C11 6.7.9 Initialization

All the expressions in an initializer for an object that has static or thread storage duration shall be constant expressions or string literals.

But both GCC/Clang accepted the following code:

const int i = 3; // const here should not make i a constant expression
static int j = i;

Even with -Wall -Wextra -Werror -pedantic-errors, the compilers above are not giving me any complaint.

However, these compilers do realize that i was not a constant expression. For example, Clang gave me:

error: size of static array must be an integer constant expression

for the following code:

const size_t sz = 3;
static int a[sz];

Am I getting anything wrong here?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You didn't miss anything, it is indeed a not a strictly conforming C program, and a non-conforming behavior on the compiler's part. This is very likely caused by the both GCC and Clang being compiler suites for C++ as well. In C++ i is a valid initializer for j.

It's worth noting however that while compilers are free to translate non-conforming C programs at their discretion, they must still issue a diagnostic about the non-conformance according to C11 5.1.1.3 p1:

A conforming implementation shall produce at least one diagnostic message (identified in an implementation-defined manner) if a preprocessing translation unit or translation unit contains a violation of any syntax rule or constraint, even if the behavior is also explicitly specified as undefined or implementation-defined. Diagnostic messages need not be produced in other circumstances.

Even if we accept the behavior as an extension, the fact GCC and Clang don't issue a diagnostic is conformance bug on both their parts.


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

...