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','\0'}; /* c is 's' */ printf("%d\n",q); /* prints 1*/ }
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:
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With