Brain Teaser

Kevin D. Quitt kdq at demott.COM
Thu Mar 29 04:05:42 AEST 1990


In article <MCDANIEL.90Mar27200111 at rollmops.amara.uucp> mcdaniel at amara.uucp (Tim McDaniel) writes:
>
>>oesterle at 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? 

kdq
-- 

Kevin D. Quitt                          Manager, Software Development
DeMott Electronics Co.                  VOICE (818) 988-4975
14707 Keswick St.                       FAX   (818) 997-1190
Van Nuys, CA  91405-1266                MODEM (818) 997-4496 Telebit PEP last
34 12 N  118 27 W                       srhqla!demott!kdq   kdq at demott.com

 "Next time, Jack, write a God-damned memo!" - Jack Ryan - Hunt for Red October



More information about the Comp.lang.c mailing list