cast'ing unions
Lazer Danzinger
lazer at mnetor.UUCP
Wed Aug 30 05:38:13 AEST 1989
In article <2189 at stl.stc.co.uk=> dsr at 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.
More information about the Comp.lang.c
mailing list