Structure question (problem)

Wayne A. Christopher faustus at ucbcad.UUCP
Sun Jun 2 05:24:01 AEST 1985


> It is very difficult to formulate a reasonable rule for union
> initialization.  The ANSI rule (initializers apply to the first member)
> is just a kludge.  The `match the types' rule plays fast and loose
> with C's type-matching rules.  Consider ucbcat!faustus's example
> (here simplified):
> union{
> 	int a;
> 	long b;
> }c[]={
> 	57,
> 	(long)76365
> };

Well, it wasn't quite that -- I had only one value in the initialization.
That's all you need, since they will overwrite each other anyway.

> ucbcat!faustus no doubt expects 57 to initialize a and 76365 to
> initialize b.  But 57 is a legal initializer for b and (long)76365
> is a legal initializer for a.

But if you had a choice it would make sense to match the types, or at
least do them in the order that they are written. If you only give one
value, then there might be some problem if you had a long and a short,
and it made a difference which one you filled in (e.g, if you filled in
the long it wouldn't have the same value as the short). In that case,
all you need is some coherent rule for what is going to happen... I
think that the "first element" rule is good enough for most purposes.

> Furthermore, this scheme cannot even be made to work.  The following
> example should indicate one reason:
> 
> union{
> 	int a;
> 	struct{
> 		int :16;
> 		int b;
> 	}c;
> }d={5};

This will work, because you will never be able to assign the integer 5 to
the structure. If you wanted to assign something to the structure you
would have to write " ... } d = { 5, { 53, 474 } } ;", which is probably
useless, because unless you know which member of the union you will use
first there's no point in initializing any of them...

	Wayne



More information about the Comp.lang.c mailing list