Type punning in C

Herman Rubin cik at l.cc.purdue.edu
Thu Oct 12 22:21:18 AEST 1989


In article <1989Oct11.091619.18336 at gdt.bath.ac.uk>, exspes at gdr.bath.ac.uk (P E Smee) writes:
> 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.

This is another example of those "gurus" who can not envision an intelligent
user using the machine in an intelligent manner, and prevent that use.  I
have deliberately used "type punning" on various machines, and I consider it
an extremely useful tool.  Now, I do not mind the compiler asking me if I
really wanted to do it, but I object to anyone telling me that I CAN NOT
use instructions that do what I want to do.

It should not even bother an optimizer.  The optimizer takes the operations
given by the programmer, in some cases applies transformations known to 
provide the same result, and optimizes the order.  Why should an integer
and a floating point number in the same location bother it, unless that
location is a register and the (expletives deleted) hardware has different
integer and floating registers?  But even that should not befuddle the
optimizer.
> -- 
>  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


-- 
Herman Rubin, Dept. of Statistics, Purdue Univ., West Lafayette IN47907
Phone: (317)494-6054
hrubin at l.cc.purdue.edu (Internet, bitnet, UUCP)



More information about the Comp.lang.c mailing list