Path: utzoo!censor!geac!torsqnt!news-server.csri.toronto.edu!cs.utexas.edu!wuarchive!zaphod.mps.ohio-state.edu!ub!uhura.cc.rochester.edu!rochester!kodak!ispd-newsserver!bilbo From: bilbo@bisco.kodak.COM (Charles Tryon) Newsgroups: comp.lang.c Subject: Re: union or type casting, which to use? Message-ID: <9011271554.AA23331@bisco.kodak.COM> Date: 27 Nov 90 15:54:47 GMT Sender: news@ssd.kodak.com Organization: Eastman Kodak Company; Rochester, NY Lines: 51 Apparently-To: inews Originator: bilbo@bisco Return-Path: In <931@laic.UUCP>, ik@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!) 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)