Rox <> wrote:
> So I presume:
> char c[10] = "";
> Will initialize c into 0. Just like memset do.
> It's such a neat way to initial a string that I can't believe it!
> Am I right?
Yes, it has been that way for a long time. In C89 (3.5.7) you
have:
| If there are fewer initializers in a list than there are members of
| an aggregate, the remainder of the aggregate shall be initialized
| implicitly the same as objects that have static storage duration.
If I'm not completely mistakent his means that this trick does
not only work for char arrays but for all kinds of arrays. So
int i[ 10 ] = { 1 };
will initialize the first element of i to 1 and the rest to 0.
(And if you use 0 as the only initializer you will get an array
with all 10 elements set to 0.)
Your example of
char c[ 10 ] = "";
is just a special case of this since it's equivalent to
char c[ 10 ] = { '\0' };
And, a more complex example directly taken from C89
| float z[4][3] = {
| { 1 }, { 2 }, { 3 }, { 4 }
| };
|
| initializes the first column of z as specified and initializes the
| rest with zeros.
I would expect this to hold also for structures, so that
struct { int i; double d; } s = { 1 };
would have the effect of setting s.i to 1 and s.d to 0.0.
This results in a warning when using gcc which complains about
a missing initializer for s.d (but seems to do the expected).
I guess gcc is a bit overzealous here at the warning level I
am using (but then a compiler is free to warn about anything
it doesn't like).
Regards, Jens
--
\ Jens Thoms Toerring ___
\__________________________
http://toerring.de