By accident I found that the line char s[] = {"Hello World"};
is properly compiled and seems to be treated the same as char s[] = "Hello World";
. Isn't the first ({"Hello World"}
) an array containing one element that is an array of char, so the declaration for s should read char *s[]
? In fact if I change it to char *s[] = {"Hello World"};
the compiler accepts it as well, as expected.
Searching for an answer, the only place I found which mentioned this is this one but there is no citing of the standard.
So my question is, why the line char s[] = {"Hello World"};
is compiled although the left side is of type array of char
and the right side is of type array of array of char
?
Following is a working program:
#include<stdio.h>
int main() {
char s[] = {"Hello World"};
printf("%s", s); // Same output if line above is char s[] = "Hello World";
return 0;
}
Thanks for any clarifications.
P.S. My compiler is gcc-4.3.4.
It's allowed because the standard says so: C99 section 6.7.8, §14:
What this means is that both
and
are nothing more than syntactic sugar for
On a related note (same section, §11), C also allows braces around scalar initializers like
which, incidentally, fits nicely with the syntax for compound literals
Any variable in (
int
,char
, etc.) is just an array of length 1.works as well.
The compiler accepets it,because actually, you're making an array 2D of undefined size elements,where you stored one element only,the
"Hello World"
string. Something like this:You can't omit the
bracets
in this case.This is allowed by the C++ standard as well, Citation:
I might be wrong, but I think this is not an array of arrays of chars, but a block contains an array of chars.
int a = {1};
may work as well.The braces are optional, and the expression is equivalent to just an array of char.
You can also write this:
Demo : http://ideone.com/z0psd
In fact,
C++11
generalizes this very syntax, to initialize non-arrays as well as arrays, uniformly. So inC++11
, you can have these: