How to initialize unions

Shankar Unni shankar at hpclscu.HP.COM
Thu Apr 6 08:01:18 AEST 1989


> >	struct ident {
> >	        char *name;
> >	        int type;
> >	        union {
> >	                double f;
> >	                int i;
> >	        } value;
> >	};
> >
> >and I want to initialize the name, type, and value.i elements of an array
> >of them them at compile time.
> 
> Unless you have an extension, you cannot do this unless you change the
> order to
> 
> 		union {
> 			int i;
> 			double f;
> 		} value;
> 
> Even then, you must have a pANS-conformant compiler or its equivalent;
> most PCCs will refuse to initialise any unions, giving the error message

And don't forget to brace-enclose the initializer of the union member, as
follows:

struct ident stuff = {
    { "abcd", KEYWORD, {KW_ABCD}},
    /*                ^^^^^^^^^^^  */
    /* ... */
};
---
Shankar



More information about the Comp.lang.c mailing list