Brain Teaser

Jan Christiaan van Winkel jc at atcmp.nl
Wed Mar 28 17:58:22 AEST 1990


>From article <10289 at wpi.wpi.edu>, by oesterle at wpi.wpi.edu (Shawn H. Oesterle):
! Problem:
! 	Swap two pointers without using a third pointer.
! Example:
! 	{
! 		void * x, * y, * tmp;
! 		tmp = x;
! 		x = y;
! 		y = x;
! 	}
! 
! 	Make a piece of code which has the same effect as this, but without
! 	using the 'tmp' variable (in C, of course).
The problem is that pointers cannot be used in arithmatic operations 
without the danger for inportability. Supposing x and y are ints (or longs),
you can do the following:
x=x^y; y=x^y; x=x^y;    /* swap x and y */

casting the pointers x and y to a long and v.v. is your responsability...
JC


-- 
=============================================================================
Jan Christiaan van Winkel         Tel: +31 80 566880              jc at atcmp.nl
AT Computing       P.O. Box 1428       6501 BK Nijmegen       The Netherlands
=============================================================================



More information about the Comp.lang.c mailing list