Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!utgpu!water!watmath!clyde!rutgers!mcnc!rti!xyzzy!throopw From: throopw@xyzzy.UUCP Newsgroups: comp.lang.c Subject: Re: typeof isn't enough to define swap correctly Message-ID: <254@xyzzy.UUCP> Date: Sat, 12-Sep-87 15:29:32 EDT Article-I.D.: xyzzy.254 Posted: Sat Sep 12 15:29:32 1987 Date-Received: Sun, 13-Sep-87 08:40:57 EDT References: <557@rocky.STANFORD.EDU> <1880@sol.ARPA> <109@umigw.MIAMI.EDU> <2019@sfsup.UUCP> Organization: Data General, RTP NC. Lines: 36 > mpl@sfsup.UUCP (M.P.Lindner) > #define swap(a, b) { \ > register int i; \ > for (i = 0; i < sizeof(a); i++) { \ > ((char *) &a)[i] ^= ((char *) &b)[i]; \ > ((char *) &b)[i] ^= ((char *) &a)[i]; \ > ((char *) &a)[i] ^= ((char *) &b)[i]; \ > } \ > } > OK, so it's not as pretty or efficient as everyone would like, but it's > completely general purpose and doesn't need any new features. No, I'm not about to pick the nit that everybody else does at this point, which is that it doesn't work for register variables. No, I'm going to pick the nit that the typebreaking done when copying things of arbitrary type as characters is first of all not guaranteed to work correctly by draft X3J11 (nor by K&R), and second of all I'm familiar with a machine on which it would have failed. In particular, imagine a type with a data format that depends upon where in memory it is located. A common example of this is executable code. To copy executable code from place to place, it is often not sufficent to treat it as an array of bytes and copy those bytes. Before you dismiss this as frivolous, there is at least one architecture where *pointers* have this property... that is, the format of the pointer depends upon where in memory it is stored. Thus, versions of "swap" that do type breaking of this kind are vulnerable to failure when fed structures containing pointers to swap, for example. Just thought y'all might be interested in this little-known bit of trivia. -- To understand a program you must become both the machine and the program. --- Alan J. Perlis -- Wayne Throop !mcnc!rti!xyzzy!throopw