Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c - int q = {1,2}; peculiar initialization list

I came across the below initialization , it is seen that VS2012 shows an error complaining about too many initializers. in GCC it seems to return the first element as the value.

why is this peculiar initialization supported in GCC?

#include <stdio.h>

int main()
{
    int q = {1,2};
    char c = {'s','t',''};  /* c is 's' */
    printf("%d
",q); /* prints 1*/
}
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

C11: 6.7.9 Initialization (p11):

The initializer for a scalar shall be a single expression, optionally enclosed in braces.

Therefore, this is allowed

int q = {1};   

You can enclose the initializer for scalar objects in braces ({}). Note the verb shall is used here. The standard says:

5.1.1.3 Diagnostics (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

So, it is up to the compiler how it handles

int q = {1,2}; 

Compiled on GCC 4.8.1 with flags -pedantic -Wall -Wextra and it raised a warning

[Warning] excess elements in scalar initializer [enabled by default]   

Now the question is: What happend with the remaining initializers? It's a bug.


Note: C11: 6.5.17 (p3) says that the comma operator cannot appear in contexts where a comma is used to separate items in a list (such as arguments to functions or lists of initializers).

Do not confused the , in {1,2} with comma operator. As Keith Thompson pointed out that, the expression in initializer to be an assignment-expression and it must not contain comma operator at top-level. That means it can be used within a parenthesized expression or within the second expression of a conditional operator in such contexts. In the function call

f(a, (t=3, t+2), c)

the function has three arguments, the second of which has the value 5.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...