Path: utzoo!mnetor!lazer From: lazer@mnetor.UUCP (Lazer Danzinger) Newsgroups: comp.lang.c Subject: Re: cast'ing unions Message-ID: <5068@mnetor.UUCP> Date: 29 Aug 89 19:38:13 GMT References: <2189@stl.stc.co.uk=> Reply-To: lazer@mnetor.UUCP (Lazer Danzinger) Organization: Motorola Computer X Lines: 36 In article <2189@stl.stc.co.uk=> dsr@stl.stc.co.uk (David Riches) writes: => =>union =>{ => int i ; => float f ; => char* c ; =>} =>UNION ; => =>UNION u ; =>u.i = 1 ; => =>Is it possible in C to typecast from an instance of the union to a variable =>having the same type as one of the component fields of the union : => =>ie float num = (float) u ; => =>I tried the above but got compiler errors. Am I doing the typecast wrong, =>or do I need to use another method to achieve the above, or is it not =>possible to do the typecast directly ?? => 1. UNION, as specified above, is not a new data type name, but a (union) variable. Hence, the "UNION u;" statement will generate a syntax error. (Unless you say: typedef union . 2. Assuming that "u" is indeed a union variable, then the following works: num = *(float *)&u; My example is consistent with the restrictions place upon unions, as specified in K&R, pg. 140: "...the only operations currently permitted on unions are accessing a member and taking the address..." ANSI 'C' may be more tolerant.