Generic Swap
Benjamin Zhu
zhu at cs.jhu.edu
Wed Jun 13 05:34:11 AEST 1990
In article <1990Jun11.214844.21531 at agate.berkeley.edu> dankg at sandstorm.Berkeley.EDU (Dan KoGai) writes:
>>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)
^^^^ ^^^^
I suppose you want to write (type *) instead. Otherwise, it
looks OK.
>
> 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)
Benjamin Zhu
+=========================================================================+
+Disclaimer: +
+ I do not represent Johns Hopkins, Johns Hopkins does not +
+ represent me either. +
+==========================================================================
More information about the Comp.lang.c
mailing list