Generic Swap

Karl Heuer karl at haddock.ima.isc.com
Tue Jun 12 02:34:47 AEST 1990


In article <1990Jun11.133729.6575 at cs.utk.edu> wozniak at utkux1.utk.edu (Bryon Lape) writes:
>generic_swap(void *, void *) {
>   void *temp;   temp = b;  b = a;  a = temp;
>}

[0] This won't even compile, since you left out the names of the arguments.
Please, people, try to post code fragments directly from the test source if
possible, rather than keying them in.

[1] You have the wrong level of indirection.  The objects to be swapped were
passed by reference, so you need to dereference them (`*a', `*b') in order to
swap the actual objects.  But you can't, because this routine doesn't know the
types of the pointed-to objects.  You could use
	void generic_swap(void *pa, void *pb, size_t n) {
	    void *ptmp = malloc(n);  assert(ptmp != NULL);
	    memcpy(ptmp, pb, n);  memcpy(pb, pa, n);  memcpy(pa, ptmp, n);
	}
but this is pretty silly.  Just code the bloody thing inline, rather than
trying to use a generic routine.

[2] Note to readers: please don't followup this thread unless you've already
read the relevant part of the Frequently Asked Questions document, and have
something *new* to say.  I don't want to see the XOR hack being discussed to
death again.

Karl W. Z. Heuer (karl at ima.ima.isc.com or harvard!ima!karl), The Walking Lint



More information about the Comp.lang.c mailing list