Swap any type of two variables in c [duplicate]

谁都会走 提交于 2019-12-13 04:33:48

问题


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.


回答1:


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.




回答2:


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; }


来源:https://stackoverflow.com/questions/19255069/swap-any-type-of-two-variables-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!