Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!wuarchive!zaphod.mps.ohio-state.edu!samsung!uunet!charyb!will From: will@kfw.COM (Will Crowder) Newsgroups: comp.lang.c Subject: Re: Brain Teaser Summary: swapping pointers without a temp probably *is* impossible Message-ID: <1990Mar29.170608.7565@kfw.COM> Date: 29 Mar 90 17:06:08 GMT References: <99@demott.COM> Reply-To: will@kfw.com (Will Crowder) Followup-To: comp.lang.c Distribution: na Organization: KFW Corporation, Newbury Park, CA Lines: 52 In article <99@demott.COM> kdq@demott.COM (Kevin D. Quitt) writes: > >(God, I love it when people say things are impossible (:-{>} ) > >void swap_pointers( x, y ) > >long *x, *y; /* whichever declaration is required */ > { > *x ^= *y; > *y ^= *x; > *x ^= *y; > } (God, I love it when people post wrong answers to the net. :) :) ) The code above swaps the longs *pointed to* by x and y, it does not swap the pointers themselves. I assume what you meant was: void swap_pointers(void **x,void **y) { *x ^= *y; *y ^= *x; *x ^= *y; } which you would then call as: int main(void) { void *x,*y; x = &something1; y = &something2; swap_pointers(&x,&y); /* * x now points to something2 and y points to something1; note * that something1 and something2 are still at the same location * in memory */ } Of course, this is not in the least bit portable, or even advisable. Avoiding a temp in this case, and retaining portability and ANSI compliance, is probably darn near impossible if not actually impossible. I can't think of any way to do it. The restrictions on the arithmetic you can do with pointers prevent any of the "wow-neato" swap methods from being used. Use a temp, save a life. Will