Type punning in C

P E Smee exspes at gdr.bath.ac.uk
Fri Oct 13 19:03:11 AEST 1989


In article <1654 at l.cc.purdue.edu> cik at l.cc.purdue.edu (Herman Rubin) writes:
>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)
>< >
>< >The Fortran standard specifies that a REAL and INTEGER occupy the same space.
>> 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.

Trust me, 'cause I don't want to get into a long discussion of FORTRAN
in a C newsgroup.  There are an incredible number of things which may
cause aliasing in FORTRAN, some of it invisible to the compiler at any
given moment due to separate compilation of modules, and so the
optimizer needs all the help it can get.  '77 FORTRAN is even more
restrictive on the user as regards possible punning and aliasing than
'66 FORTRAN was, in order primarily to permit more reliable optimization.

The need for a construct to permit type punning is clear, particularly
if you're doing 'systemmy' work.  People working on the Algol compiler
on Multics (which does even more stringent, and cross-module, type
checking) resorted to writing little PL/1 routines which simply took
whatever they were given and passed it straight back,
unchanged(bitwise) -- and declared them in the Algol code as 'foreign'
('other language module, suspend type checking') 'takes integer returns
real'.  Lies, in other words.

I tend to like things which match PL/1's 'unspec' in concept.  This
provides an explicit instruction to the compiler, and (more
importantly) a warning to future maintainers of the code, that you are
about to willfully, knowledgeably, and intentionally, cheat the data
typing and conversion rules.  Every serious language should have such a
thing.  (Unfortunately, it seems that most don't, sigh...)

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