Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!seismo!rutgers!mit-eddie!genrad!decvax!ima!haddock!karl From: karl@haddock.UUCP (Karl Heuer) Newsgroups: comp.lang.c Subject: Re: union initialization Message-ID: <455@haddock.UUCP> Date: Mon, 27-Apr-87 14:20:08 EDT Article-I.D.: haddock.455 Posted: Mon Apr 27 14:20:08 1987 Date-Received: Tue, 28-Apr-87 02:55:36 EDT References: <3290@burdvax.PRC.Unisys.COM> <1722@plus5.UUCP> Reply-To: karl@haddock.ISC.COM.UUCP (Karl Heuer) Organization: Interactive Systems, Boston Lines: 44 Summary: summary of possibilities, and a new proposal In article <1722@plus5.UUCP> hokey@plus5.UUCP (Hokey) writes: >In my opinion, [ANSI's] mechanism is *worse* than not having *any* way to >perform compile-time initialization of unions. First off, let me state that I think that initializing a union is a perfectly valid thing to want to do. Let's look at some of the possibilities: K&R says it can't be done. This is annoying; it requires one to use run-time initialization or non-portable kludges (including, perhaps, writing the definition in assembly language). ANSI proposes that unions be initializable, but only to their first member. The sudden introduction of a distinguished member of a (previously unordered) union bothers me a bit; I feel they're attacking the symptom instead of the problem. Also, this proposal doesn't always help: the initialization { a[0].asfloat = 17.5, a[1].asstring = "hello" } still can't be performed at compile time. A cast to union type would fix this (the example would then read union floatstr a[2] = { (union floatstr)17.5, (union floatstr)"hello" }; ), but this could still cause problems -- if a union includes a char member as well as an int member, how does one initialize the char? (Recall that C has no rvalues of type char.) Here's my new proposal: I think what I'd like to see is a syntax for initializing an aggregate by name rather than position. Something like union floatstr a[2] = { { asfloat: 17.5 }, { asstring: "hello" } }; (the outer braces are for the array, the inner ones for the union). This would also apply to structs, so one could initialize a struct without having to know the number or order of the members: struct tm today = { tm_year: 87, tm_mon: 4, tm_mday: 27 }; (Other elements would, as usual, be initialized to zero (if the struct is static) or garbage (if auto).) This could even be extended to arrays: int a[30] = { 29: -1 }; /* an array with a -1 in the last position */ I would find this last feature useful when dealing with an array which is logically subscripted by an enum: int val[NCOLORS] = { RED: 0x00f, GREEN: 0x0f0, WHITE: 0xfff }; The primary objection to this scheme, I think, is that it is a significant addition to the language. Karl W. Z. Heuer (ima!haddock!karl or karl@haddock.isc.com), The Walking Lint