Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!amdahl!ames!hao!oddjob!mimsy!chris From: chris@mimsy.UUCP (Chris Torek) Newsgroups: comp.lang.c Subject: Re: initialization of unions Message-ID: <9155@mimsy.UUCP> Date: Thu, 29-Oct-87 13:43:06 EST Article-I.D.: mimsy.9155 Posted: Thu Oct 29 13:43:06 1987 Date-Received: Wed, 4-Nov-87 02:49:11 EST References: <165600017@uiucdcsb> <4237@ccv.bbn.COM> <1936@killer.UUCP> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 51 >In article <4237@ccv.bbn.COM> kgregory@ccy.bbn.com (Keith D Gregory) writes: >>...unions are initialized as if you were initializing their first element... In article <1936@killer.UUCP> chip@killer.UUCP (Chip Rosenthal) writes: >... Is there some reason I'm overlooking why the compiler couldn't let >you cast it to one of the following elements? Yes. Casts do not carry enough information if you work under `expression' rules, where types char, short, and float get short shrift, being immediately promoted to longer types. Moreover, you cannot cast aggregates, so that union { struct intnode { int type; int i; } intnode; struct floatnode { int type; float f; } floatnode; ... } x = { (struct floatnode) { FLOATTYPE, 4.5 } }; is not possible. If, however, you were to announce that, because there is no clean and simple solution, that unions were never to be initialised at all, you would not be able to pin down the initial value of an uninitialised union: union { int i; char *p; } global_x; Yet all global variables are supposed to be initialised to `zero', even if that results in a nonzero bit pattern: char *p; char *q = 0; are the same if both variables are global (or static), while it is conceivable that both have the bit pattern that corresponds to 0xc0000000. (This pattern guarantees an error if dereferenced on a Vax.) What, then, is the value of `global_x' above? The X3J11 committee has decided that the value is such that the first element of the union will compare equal to zero, so on our hypothetical Vax compiler that makes zero `char *' values 0x80000000, global_x.i is 0, not 0x80000000. -- In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7690) Domain: chris@mimsy.umd.edu Path: uunet!mimsy!chris