Generic Swap

Dan KoGai dankg at sandstorm.Berkeley.EDU
Tue Jun 12 07:48:44 AEST 1990


>swap the actual objects.  But you can't, because this routine doesn't know the>...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.

	I agree:  Usually we don't swap objects so large that requires
memcpy().  Instead we swap pointers to the objects.  But C sometimes
allows assignment of objects larger than size of register, such as
structs and some compilers allow to pass structs as arguments (not ptr
to structs).  Here's my quick & dirty macro

void *temp;
#define swap(type, x, y) temp = (type *)malloc(sizeof(type));\
	*(type)temp = x; x = y ; y = *(type)temp; free(temp)

	Since this is a macro, it should work even though your compiler
does not allow passing structs as arguments (struct assignment is valid
since K&R while struct as argument is not).  But since it's a macro,
handle with care (even better for C++ #inline)

>[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.

	Since I haven't seen my macro version, I decided to follow.

Dan Kogai (dankg at ocf.bekeley.edu)



More information about the Comp.lang.c mailing list