Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!wuarchive!gem.mps.ohio-state.edu!ginosko!uunet!mcsun!ukc!dcl-cs!gdt!gdr!exspes From: exspes@gdr.bath.ac.uk (P E Smee) Newsgroups: comp.lang.c,comp.sys.super Subject: Re: Type punning in C Message-ID: <1989Oct11.091619.18336@gdt.bath.ac.uk> Date: 11 Oct 89 09:16:19 GMT References: <475@idacrd.UUCP> <1989Oct10.185851.6490@agate.berkeley.edu> Reply-To: exspes@gdr.bath.ac.uk (P E Smee) Organization: University of Bristol c/o University of Bath Lines: 30 In article <1989Oct10.185851.6490@agate.berkeley.edu> jerry@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@uk.ac.bristol Computer Centre | BITNET: Smee%uk.ac.bristol@ukacrl.bitnet University of Bristol | Internet: Smee%uk.ac.bristol@nsfnet-relay.ac.uk (Phone: +44 272 303132) | UUCP: ...!mcvax!ukc!gdr.bath.ac.uk!exspes