union or type casting, which to use?
Ik Su Yoo
ik at laic.UUCP
Tue Nov 27 11:26:35 AEST 1990
(Excuse me if this question is covered in the FAQ list.)
Suppose I have the following typedefs:
typedef struct _foo { /* foo def */ } foo;
typedef struct _bar { /* bar def */ } bar;
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;
better (or worse) than
#include <sys/types.h>
typedef struct {
int type; /* 0 for foo pointer, 1 for bar pointer */
caddr_t item;
} oneof2;
In the second method, the `item' field will be type casted to (foo *)
or (bar *) as necessary.
One of the major need is to be able to statically initialize the
`item' field. If the first method is better, how do I initialize the
`item' field? I don't care much for inefficiency due to run-time type
casting.
Thanks in advance.
--
| Ik Su Yoo | Office: (415) 354-5584 |
| Scientist @ Lockheed AI Center | Fax: (415) 354-5235 |
| Orgn. 96-20, Bldg. 259, 3251 Hanover St. | E-mail: ik at laic.lockheed.com |
| Palo Alto, CA 94304-1191 | ...!leadsv!laic!ik |
More information about the Comp.lang.c
mailing list