I need to define a preprocessor macro swap(t, x, y) that will swap two arguments x and y of a given type t in C/C++.Can anyone have any opinion on how can i do it?
Asked
Active
Viewed 3,834 times
-4
-
1possible duplicate of [is there an equivalent of std::swap() in c](http://stackoverflow.com/questions/2637856/is-there-an-equivalent-of-stdswap-in-c) – 2501 Oct 25 '14 at 12:47
-
1Why do you need a macro in C++ if there is std::swap? – sasha.sochka Oct 25 '14 at 12:49
-
2Use #define SWAP (t, x, y) do{t tmp = (x); (x) = (y); (y) = tmp;} while(0) Terminating semicolon omitted to make use look like a function call. – midor Oct 25 '14 at 13:06
-
i want to conform that, the type that you have specified means any of these (int,float,char,... etc). – Manjunath N Oct 25 '14 at 13:36
1 Answers
4
If you want to swap basic types like int or char (which implement the XOR operator) you can use the tripple XOR trick to swap the values without the need of an additional variable:
#define SWAP(a, b) \
{ \
(a) ^= (b); \
(b) ^= (a); \
(a) ^= (b); \
}
If you're swapping complex types (float, structs, ...) you need a helper variable:
#define SWAP_TYPE(type, a, b) \
{ \
type __swap_temp; \
__swap_temp = (b); \
(b) = (a); \
(a) = __swap_temp; \
}
Usage of those two macros is like this:
int a = 6;
int b = 123;
float fa = 3.1415;
float fb = 2.7182;
SWAP(a, b);
SWAP_TYPE(float, fa, fb);

Lukas Thomsen
- 3,089
- 2
- 17
- 23