Brain Teaser

Will Crowder will at kfw.COM
Fri Mar 30 03:06:08 AEST 1990


In article <99 at demott.COM> kdq at 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



More information about the Comp.lang.c mailing list