Path: utzoo!attcan!uunet!wuarchive!brutus.cs.uiuc.edu!apple!bionet!csd4.csd.uwm.edu!mailrus!ncar!ico!ism780c!news From: news@ism780c.isc.com (News system) Newsgroups: comp.lang.c Subject: Re: swap(x,y) Message-ID: <32074@ism780c.isc.com> Date: 24 Aug 89 20:01:00 GMT References: <8350@boring.cwi.nl> <8514@galbp.LBP.HARRIS.COM> <3040@solo5.cs.vu.nl> Reply-To: marv@ism780.UUCP (Marvin Rubenstein) Organization: Interactive Systems Corp., Santa Monica CA Lines: 31 In article <3040@solo5.cs.vu.nl> maart@cs.vu.nl (Maarten Litmaath) writes: >jsb@advdev.LBP.HARRIS.COM (FLEA) writes: >\In article <8350@boring.cwi.nl> tromp@piring.cwi.nl (John Tromp) writes: >\: (Timothy R. Gottschalk) writes: >\... >\:> x += y; >\:> y = x - y; >\:> x -= y; >\... >\Sorry, folks, both of these are illegal if x and y are pointers. > >Or if they're structs! :-) It is obvious to the casual observer that the above is illegal if the operations + and - are not defined for the data. The question really is: for the case where the program segment (as written) compiles, will it swap the values of x and y. The answer is that it will work on two's complement binary machines that ignore overflow and carry out provided x and y are the same integral type. It does not work when the types differ (for example char x; long y;). It also does not work for all values of floating types. But most important, it is a bad piece of code for two reasons. 1) it is obtuse and 2) it requires more space and time than the simpiler: temp=x; x=y; y=temp; As may have been pointed the EXOR method may be faster then the above for a machine like the 370 that provides a memory to memory EXOR operation on data blocks. But there is no way to express such an operation in C. Marv Rubinstein