Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!usc!zaphod.mps.ohio-state.edu!mips!prls!pyramid!leadsv!laic!ik From: ik@laic.UUCP (Ik Su Yoo) Newsgroups: comp.lang.c Subject: union or type casting, which to use? Keywords: union, type casting, static initialization Message-ID: <931@laic.UUCP> Date: 27 Nov 90 00:26:35 GMT Distribution: usa Organization: Lockheed AI Center, Menlo Park Lines: 44 (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 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@laic.lockheed.com | | Palo Alto, CA 94304-1191 | ...!leadsv!laic!ik |