Union initialization

Karl Heuer karl at haddock.ima.isc.com
Fri Feb 24 08:26:08 AEST 1989


In comp.lang.c article <437 at lakart.UUCP> dg at lakart.UUCP (David Goodenough)
suggests that union initialization could be done thus:
>union { float f; int i; char *c; } u[3] = {
>    { 1.0 ; ; },	/* could also be { 1.0 } - trailing ; are optional */
>    { ; 76 ; },	/* ditto: { ; 76 } would also be OK */
>    { ; ; "STUG" }
>};

Not bad, but I see no reason to use semicolon as the separator.  Comma is
already used in this context for struct initializers, so it would be more
consistent to use the same token for unions.  (No, this would not conflict
with the comma operator.)

In fact, one could even generalize the notation to allow missing expressions
in a struct or array initializer: int a[3]={3, ,5} would initialize a[0]=3,
a[2]=5, and leave a[1] uninitialized (zero or garbage, depending on storage
duration).

However, initializing by position may be a mistake anyway; it requires the
application to know the order of the members.  This information is often
deliberately left unspecified.  If we're going to tweak the language, let's
try to do it in a way that will assist with this sort of data abstraction.

Would the following be workable?
	int a[3] = { 0: 3, 2: 5 };
	union { float f; int i; char *c; } u[3] = {
	    { f: 1.0 },
	    { i: 76 },
	    { c: "STUG" }
	};

Karl W. Z. Heuer (ima!haddock!karl or karl at haddock.isc.com), The Walking Lint
Followups to comp.lang.misc; we're talking `D' again.



More information about the Comp.lang.c mailing list