union or type casting, which to use?

Charles Tryon bilbo at bisco.kodak.COM
Wed Nov 28 02:54:47 AEST 1990


In <931 at laic.UUCP>, ik at laic.UUCP (Ik Su Yoo) asks:
> Suppose I have the following typedefs:
> 
>   typedef struct _foo { /* foo def */ } foo;
>   typedef struct _bar { /* bar def */ } bar;

  One side note:  Avoid using names beginning with underscores.  These names
  are reserved for the system to use, and could break things which would be
  VERY hard to track down.

  I use something like this:
        typedef struct bar { /* bar def */ } Bar;
                                             ^^^
                            All my typedef'ed names start with Ucase letters.

> I want to create a new typedef with a field to hold a pointer to
> either `foo' or `bar'. Is there any pros/cons of using union vs.
> (explicit) type casting? For instance, is
> 
>   typedef struct {
>     int type; /* 0 for foo pointer, 1 for bar pointer */
>     union {
>       foo *f;
>       bar *b;
>     } item;
>   } oneof1;

  Again, in order to make things more readable later on (i.e., less prone to
  misunderstandings and errors :-), I would use a pair of #defined constants,
  or even better, an enum, for your type identifier, rather than 0/1.

        enum {FOO_TYPE, BAR_TYPE} Type;

> One of the major need is to be able to statically initialize the
> `item' field. ...

  Hummm...  Now, after all of this, I'm not going to answer your real question.
  I don't know if you can staticly initialize a union.  Sorry.  :-/

> |  Ik Su Yoo

--
Chuck Tryon
    (PLEASE use this address, as Kodak foobars one in header!)
    <bilbo at bisco.kodak.com>
    USmail: 46 Post Ave.;Roch. NY 14619                       B. Baggins
    <<...include standard disclamer...>>                      At Your Service

  "Swagger knows no upper bound, but the laws of physics remain unimpressed."
                                                            (D. Mocsny)



More information about the Comp.lang.c mailing list