Type punning in C

P E Smee exspes at gdr.bath.ac.uk
Wed Oct 11 19:16:19 AEST 1989


In article <1989Oct10.185851.6490 at agate.berkeley.edu> jerry at violet.berkeley.edu ( Jerry Berkman ) writes:
>
>Why not use equivalence?
>	INTEGER I
>	REAL X, IX
>	EQUIVALENCE (X,IX)
>
>	IX = I
>The Fortran standard specifies that a REAL and INTEGER occupy the same space.
>The only problem is this might fool some optimizers.
>
Problem is, the Fortran standard *also* says that if your program tries
to take the value of the variable using a different type than the type you
used when you last stored into it, your program is invalid.  This is a
polite way of saying (to the user) 'this trick may not work', and (to the
compiler writer) 'your optimizer does not have to worry about aliasing
between variables of different types'.  If the compiler can tell that
you are going to (e.g.) store an integer into that storage, and then
read a real, it is under no obligation to make sure that the integer
value gets stored.

Fortran equivalence was designed toallow reuse of storage on the early
small memory machines -- not to allow type punning.  Usually you can
get away with punning, but it doesn't always work and so is a bad habit.

-- 
 Paul Smee               |    JANET: Smee at uk.ac.bristol
 Computer Centre         |   BITNET: Smee%uk.ac.bristol at ukacrl.bitnet
 University of Bristol   | Internet: Smee%uk.ac.bristol at nsfnet-relay.ac.uk
 (Phone: +44 272 303132) |     UUCP: ...!mcvax!ukc!gdr.bath.ac.uk!exspes



More information about the Comp.lang.c mailing list