Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!csd4.csd.uwm.edu!cs.utexas.edu!romp!shaffer!jon From: jon@shaffer.UUCP (Jon Doran/60000) Newsgroups: comp.lang.c Subject: Re: swap(x,y) Summary: exclusive-or will swap without temp variables Message-ID: <2578@shaffer.UUCP> Date: 24 Aug 89 15:01:04 GMT References: Organization: IBM AWD, Austin, TX Lines: 25 In article , tg1e+@andrew.cmu.edu (Timothy R. Gottschalk) writes: > > To swap two variables x,y in C without using a temporary variable: > > /* begin swap */ > x += y; > y = x - y; > x -= y; > /* end swap */ I don't know about that, seems that overflow is a possibility... Something that I've used (mainly in assembly code) is: x ^= y; y ^= x; x ^= y; To verify that the above works (x and y must be the same size of a variable...) choose appropriate values for x and y, represent these in binary on paper, then perform the exclusive ors manually. This is perhaps the best explaination. Jon Doran IBM AWD, Austin TX