[net.lang.c] Union initialization: None of this name-the-type B.S.

kpmartin@watmath.UUCP (Kevin Martin) (10/25/84)

I have this gut feeling that specifying the union element in an initializer
according to its type is going to cause trouble somewhere. I'm not sure where
yet, though. At first I thought that
	union {
		unsigned f1:1;
		unsigned f2:2;
	} x;
would cause trouble, but you can't put fields in unions (there is no good
reason why not, except that k&r disallows it).

The proposed scheme does require adding to the language, to allow
initializing unions of structures (the cast would have to go outside
the '{' which opens the structure).

If we are going to add to the language for this, we should do it right,
and just name the element we want to get. None of this name-the-type BS.

Also consider that normal C type conversions still take place, so
	union {
		double y;
		int x;
	} foo = (long) 0;	/* oops! meant double */
initializes foo.x rather than the intended foo.y, no error message. It isn't
fumble-mind proof.

I suggest the syntax (see k&r appendix A, section 8.6):
	initializer-list:
		elem-spec(opt) expression
		initializer-list, initializer-list
		elem-spec(opt) { initializer-list }

	elem-spec:
		union-elem =          /* for unions */

The above example would then be
	union {
		double y;
		int x;
	} foo = { x = 0 };		/* {} not necessary */
That makes muddle-minded typos a bit easier to catch. It also means that
a union buried in the guts of a larger structure will get an error message
rather than mis-initialized if a comma or curly brace is misplaced.

Later, this could be extended to allow arrays and structures to
be initialized in other than sequential order, but I
am not sure what to do when one particular element is not initialized, nor
am I sure if arrays should be initialized in random order, nor can I figure
out the size of an array of unspecified size by counting initializers any more.

However, I think that naming the union element is far superior to naming
the type of the element. Both schemes require extending the language.
                 Kevin Martin, UofW Software Development Group