Initialization of unions under ANSI C

Hokey hokey at plus5.UUCP
Tue Oct 23 09:01:14 AEST 1984


I asked why unions were initialized using the first element, and received
this reply:

> From: wucs!seismo!harvard!wjh12!kendall
> To: plus5!hokey
> Subject: ANSI initialization of unions
> References: <504 at plus5.UUCP>
> 
> The ANSI C rule for initialization of unions (use the first member)
> is there because there is no syntax for indicating which member of a
> union you want to initialize.
> 
> 	Sam Kendall	  {allegra,ihnp4,ima,amd}!wjh12!kendall
> 	Delft Consulting Corp.	    decvax!genrad!wjh12!kendall

My point is, it doesn't matter.  If the data used to initialize the
union is appropriately cast, and that data type is a valid member of
the union, then there is no ambiguity nor problem; the union will hold
the value by definition, and the data will be appropriately cast.

Note that there is no ambiguity even when initializing a list of items
inside a union: the initializer-list could be cast, or the first element
of the list could be cast.

The following is *not* a well-thought-out example.  Please bear with me:

	#define CHAR	01
	#define SHORT	02
	#define LONG	03
	#define FLOAT	04
	#define DOUBLE	05
	#define SHORT_A	06

	struct {	/* I know it doesn't have a name */
	    int	CellType;	/* holds one of the above defines */
	    union {
		char	cv_char;
		short	cv_short;
		long	cv_long;
		float	cv_float;
		double	cv_double;
		short	cv_short_a[4]
	    } cv;
	} cell[10] = {
	/*0*/ {CHAR,	'?'},	/* cast isn't needed in this case */
	/*1*/ {DOUBLE,	(double)2},
	/*2*/ {SHORT_A,	(short[]){0, 1, 2}}	/* last element is 0? */
	};

Shoot away!  (This is the sort of thing I'd like to discuss in mod.std.c)
-- 
Hokey           ..ihnp4!plus5!hokey
		  314-725-9492



More information about the Comp.lang.c mailing list