[comp.lang.c] cast'ing unions

dsr@stl.stc.co.uk (David Riches) (08/11/89)

Here's a posting for a friend, replies to ME please:-
------
I have a question regarding the "union" construct in the C programming language
which I need answering urgently.

Consider the following union construct :

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 ??

   Dave Riches
   PSS:    dsr@stl.stc.co.uk
   ARPA:   dsr%stl.stc.co.uk@earn-relay.ac.uk
   Smail:  Software Design Centre, (Dept. 103, T2 West), 
	   STC Technology Ltd., London Road,
	   Harlow, Essex. CM17 9NA.  England
   Phone:  +44 (0)279-29531 x2496

gwyn@smoke.BRL.MIL (Doug Gwyn) (08/12/89)

In article <2189@stl.stc.co.uk> dsr@stl.stc.co.uk (David Riches's friend) writes:
>ie float num = (float) u ;

This shows a misunderstanding not only of unions but also of casts.
A cast performs a conversion between two data types, while a union
allows multiple data types to be stored in overlapping locations
(only one type at a time is valid, though; if you store a type into
a union you need to fetch the data as the same type as was stored).

Just use	num = u.f;
or		num = (float) u.i;
depending on which one you really mean.

lazer@mnetor.UUCP (Lazer Danzinger) (08/30/89)

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.