[comp.lang.c] How to initialize unions

roy@phri.UUCP (Roy Smith) (04/05/89)

I've got a structure which looks like:

	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.  Trying the obvious:

struct ident idlist[] = {
	{"foo", KEYWORD, KW_FOO},
	{"bar", KEYWORD, KW_BAR},
	{"baz", KEYWORD, KW_BAZ}
};

draws an error from the compiler, "operands of = have incompatible types"
for each of the 3 lines.  Is there any way to do what I want to do?
-- 
Roy Smith, System Administrator
Public Health Research Institute
{allegra,philabs,cmcl2,rutgers,hombre}!phri!roy -or- roy@phri.nyu.edu
"The connector is the network"

chris@mimsy.UUCP (Chris Torek) (04/05/89)

In article <3742@phri.UUCP> roy@phri.UUCP (Roy Smith) writes:
>I've got a structure which looks like:
>
>	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

>"operands of = have incompatible types"

GCC should do the job, with the re-ordered union.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris@mimsy.umd.edu	Path:	uunet!mimsy!chris

shankar@hpclscu.HP.COM (Shankar Unni) (04/06/89)

> >	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