Re: Why not unions



Alex Fraser wrote:
> "Rob Thorpe" <robert.thorpe@xxxxxxxxxxxx> wrote in message
> news:1122490853.570267.241310@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
> [snip]
> > In C there are two main uses of unions:
> > 1. To save space by using a single location to store many types of
> > data.
> [snip]
> > union bar {
> > int x;
> > double y;
> > }
> > struct foo {
> > enum thing what_it_is;
> > union bar b;
> > }
> >
> > foo.what_it_is describes what is in the union b, it could have values
> > DOUBLE or INT for example.
> >
> > It's only worth making this a union if we need the space. If we don't
> > then we could use:
> >
> > struct foo {
> > enum thing what_it_is;
> > int x;
> > double y;
> > char *z;
> > }
> >
> > Which is simpler and easier to check.
>
> Why do you think that?

If all foos are initiated to a known state, say 0 in the x,y and z
fields, then you can perform some checking on correctness of
foo.what_it_is. If what_it_is says it's a double, but y is zero you
know it's wrong. It can be harder if everything is in one pot, y is
say 5.63322678e16 which may be correct, or maybe a mislabeled char *.
To avoid the risk of mislabeling it's best to access these things
indirectly anyway.

> FWIW, I would generally use an "unnamed" (not sure if that is the correct
> term) union type declared inside the struct:
>
> struct foo {
> enum thing what_it_is;
> union {
> int x;
> /* etc */
> } b;
> };

That's also a good way to do it, but sometimes it's useful to have the
union around to use by itself.

.



Relevant Pages

  • Re: Union trouble
    ... Is there a way of using unions transparently, so that the union name doesn't ... enum foo_type {INT, DOUBLE}; ... struct foo f0, f1; ...
    (comp.lang.c)
  • Re: union question
    ... If a union is defined ... > unsigned int aWord; ... The reason for struct and union tags is to provide the compiler a name ... 'struct foo' as though it were a type and define structures.. ...
    (comp.lang.c)
  • Re: [releng_6 tinderbox] failure on sparc64/sparc64
    ... If you have a struct foo and try to access it as an array ... It does not matter if you do it with a union or by casting ... So the proper fix for the above code is: ...
    (freebsd-arch)
  • Re: [releng_6 tinderbox] failure on sparc64/sparc64
    ... If you have a struct foo and try to access it as an array ... It does not matter if you do it with a union or by casting ... So the proper fix for the above code is: ...
    (freebsd-arch)
  • Re: Unions in structures
    ... I have never read that a union type reference is optional in any ... does not need to have a struct tag. ... A "struct tag" is an identifier that can be combined ... and `struct foo' is the name of the type. ...
    (comp.lang.c)