Standard for union initialization?
Kevin Martin
kpmartin at watmath.UUCP
Fri Jan 18 11:32:36 AEST 1985
In article <4930 at utzoo.UUCP> henry at utzoo.UUCP (Henry Spencer) asks:
>> Either way, this is less clear than an initializer of the form
>> element = value
>> e.g.
>> union {
>> <type1> foo;
>> <type2> bar;
>> <type3> mumble;
>> }baz = mumble = <initializer>;
>
>How do you use this to initialize a union inside a structure?
struct foo {
int bar;
char *blech;
union {
float float_val;
char char_val;
long long_val;
} onion;
};
struct foo x = {
42, /* value for x.bar */
"value for x.blech",
char_val = 'x' /* value for x.onion.char_val */
}; /* value for x */
-or- (adding full {}'s)
struct foo x = {
42, /* value for x.bar */
"value for x.blech",
{
char_val = 'x' /* value for x.onion.char_val */
} /* value for x.onion */
}; /* value for x */
And, seeing as I see the next question coming...
>How do yo initialize a structure inside a union?
Well, this is where your YACC grammer may actually need changes (but this
applies to the name-the-type suggestion too...)
union foo {
int bar;
char *blech;
struct {
float fred;
char herbie;
long harry;
} stroct;
};
union foo x = {
stroct = {
4.2, /* value for x.stroct.fred */
'x', /* value for x.stroct.herbie */
0x12345678 /* value for x.stroct.harry */
} /* value for x.stroct */
}; /* value for x */
-or- (removing extra {} )
union foo x =
stroct =
4.2, /* value for x.stroct.fred */
'x', /* value for x.stroct.herbie */
0x12345678 /* value for x.stroct.harry */
; /* value for x */
(You would need the inner {} in this example, say, if you wanted
x.stroct.harry to be *implicitly* initialized to zero)
Kevin Martin, UofW Software Development Group
More information about the Comp.lang.c
mailing list