Is there any logic in c which can swap any type of two variables. i.e int, float, sequence of character.
I can think of a logic of storing every type of variables as sequence of characte and swap it like normal string but i does not its good idea.
Is there any logic in c which can swap any type of two variables. i.e int, float, sequence of character.
I can think of a logic of storing every type of variables as sequence of characte and swap it like normal string but i does not its good idea.
Let's see how you'd do this for two char
variables. You'd do something like this.
void swap(char* a, char* b)
{
char tmp = *a;
*a = *b;
*b = tmp;
}
For two int
variables:
void swap(int* a, int* b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
And so on. Now, for catering to any type of variable, you'd be tempted to do:
void swap(void* a, void* b)
{
// ...
}
But you'd need to allocate a space of a parameterized size. So, you'll have to first receive that size as a parameter:
void swap(void* a, void* b, size_t s)
{
// ...
}
...which you'll pass as an argument using a sizeof
expression. And you'll need to allocate said space and do assignments (copies) using that. Off the top of my head, malloc
/free
and memcpy
come to mind, so a crude way to do what we did above for char
and int
, but this time with a parameterized size, would be:
void swap_any(void* a, void* b, size_t s){
void* tmp = malloc(s);
memcpy(tmp, a, s);
memcpy(a, b, s);
memcpy(b, tmp, s);
free(tmp);
}
As I described, this is a little crude. You could try doing it with alloca
(which allocates on the stack) and no free
.
Alternatively, you could do it with a macro, since you can pass a type (instead of a size_t
) to a macro - because macros essentially work using text replacement. Then, you can obviously create the temporary variable type by name, like this:
#define swap_m(a, b, t) { t tmp = a; a = b; b = tmp; }
Obviously, if you don't want to pass any information at all about the involved types, you'd have to be more creative about it.
You can use a macro for that, but it won't work for everything:
#define SWAP(a,b) { __typeof__(a) temp; temp = a; a = b; b = temp; }