Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!cs.utexas.edu!texbell!cpsolv!rhg From: rhg@cpsolv.CPS.COM (Richard H. Gumpertz) Newsgroups: comp.lang.c Subject: casting to/from union types Message-ID: <523@cpsolv.CPS.COM> Date: 31 May 90 03:31:30 GMT Reply-To: rhg@cpsolv.uucp (Richard H. Gumpertz) Organization: Computer Problem Solving, Leawood, Kansas Lines: 40 It is possible to effectively cast a union type to one of its component types by appending ".X" where X is the name of the component. Unfortunately, there is no way to do the reverse cast; instead one has to allocate a temporary and then assign to the temporary. For example, to pass an int I to a function that takes a union argument, one might use: extern int I; typedef union { int I; float F; } U; extern foo(int which, U x); U tempU; foo(1, (tempU.I = I, tempU)); A much cleaner syntax (to read) might be: foo(1, (U)I); A problem arises is if one wants to pass a constant: the type of constants is non-intuitive. For example, if we change the above typdef to typedef union { int I; float F; char C; } U; and then call foo(3, (U)'X'); then should the 'X' be effectively assigned to the I field or the C field? I suppose we could disambiguate between th I and C fields using a whole new kludge like foo(3, (U.C)'X'); but that seems ugly. Does anybody have a better idea as to how one might allow casting arguments to functions that accept union types without having to allocate a temporary? The details are non-obvious. Could the people on the net invent an extension that would read cleanly, maybe get some trial use, and perhaps even be proposed for inclusion for C-95 or whatever? Please reply via e-mail and I will summarize. -- ========================================================================== | Richard H. Gumpertz rhg@CPS.COM (913) 642-1777 or (816) 891-3561 | | Computer Problem Solving, 8905 Mohawk Lane, Leawood, Kansas 66206-1749 | ==========================================================================