Click to See Complete Forum and Search --> : (c) universal swap function?


rocketpcguy
02-22-2006, 11:54 AM
if i want to swap two things, i have to make many functions, for each type (int, char, etc). is there a way to make them into one function?
eg. for int, i have:

void swapint(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}

but for char, i have to copy and paste it and replace int with char!

deathadder
02-22-2006, 12:00 PM
I don't think you can, I know its possible in C++ using templates. So unfortinually it looks like your going to have to copy and paste the function for each data type you want.

JayMan8081
02-22-2006, 01:05 PM
Could you simply make the arguments to swap be of type void* and simply cast your int, char, float, etc. to void* when you pass them into the function? I do most of my programming in C++ so I don't know if this will work in C, but I'm pretty sure you could do it with C++. HTH.

bwkaz
02-22-2006, 08:01 PM
As far as casting to void*, that would allow you to get a valid function signature, but how are you going to decide what type to cast the void* back to in the code inside the swap function? You can't dereference a void pointer. ;)

rocketpcguy -- what I'd do is come up with a #define, something like:

#define makeswapfunc(type) void swap##type(type *a, type *b) { \
type temp = *a; \
*a = *b; \
*b = temp; \
} Then have several of these:

makeswapfunc(char)
makeswapfunc(int)
makeswapfunc(float)
makeswapfunc(double) Then you can call:

swapchar(&ch1, &ch2);

swapint(&i1, &i2);

/* etc., etc. */ This may not be the cleanest, but it should work. (It's basically duplicating exactly what C++ templates do, except they only have the makeswapfunc "calls" happen if you use the associated type somewhere.)

(This is the kind of thing where a type-less language like Python or Lisp or Perl would help. Then you don't have to generate different functions for different types; you can create just one function and call it with 2 references to any 2 values. But oh well. :))

rocketpcguy
02-22-2006, 08:09 PM
thank you so much bwkaz, i will do that.