Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!tut.cis.ohio-state.edu!ucbvax!ulysses!cjc From: cjc@ulysses.att.com (Chris Calabrese) Newsgroups: comp.lang.c Subject: Re: Brain Teaser Summary: no, this doesn't work on all architectures Message-ID: <12726@ulysses.att.com> Date: 28 Mar 90 22:38:38 GMT References: <99@demott.COM> Organization: AT&T Bell Laboratories, Murray Hill Lines: 47 In article <99@demott.COM>, kdq@demott.COM (Kevin D. Quitt) writes: > In article mcdaniel@amara.uucp (Tim McDaniel) writes: | > | >>oesterle@wpi.wpi.edu (Shawn H. Oesterle) asks how to swap two pointers | >>without using a third pointer. | > | >You can't do portably swap arbitrary legal pointer values without | >using an intermediate variable. In short, "no". | ???????????? | | (God, I love it when people say things are impossible (:-{>} ) | | I originally just mailed the answer, since I didn't want to clutter the | net. However... | | | void swap_pointers( x, y ) | | long *x, *y; /* whichever declaration is required */ | { | *x ^= *y; | *y ^= *x; | *x ^= *y; | } | | | Or you can do it in-line. (Seems silly to do it either way, but | this *is* a puzzle, not a request for practical code). Note that this | technique can actually be used to exchange two (presumably large) | strings - it's insensitive to data type or contents, and cannot cause | overflow or any other error condition that wouldn't happen by reading or | writing the same locations. | | Disclaimer: This assumes that pointers are not longer than longs (or | some other defined type). On the other hand, how many machines do you | know that have longer addresses than data? NO, NO, NO, NO, NO!!! This only works on machines where a pointer is a simple number!!! It doesn't work on machines with segmented architecture (intel, etc). And, it doesn't work on machines with different sized pointers for different types of pointers (Dual 86/80?). -- Name: Christopher J. Calabrese Brain loaned to: AT&T Bell Laboratories, Murray Hill, NJ att!ulysses!cjc cjc@ulysses.att.com Obligatory Quote: ``Anyone who would tell you that would also try and sell you the Brooklyn Bridge.''