Swap macro's which take a type are fairly well known.
#define SWAP(type, a_, b_) do { \
type SWAP, *a = &(a_), *b = &(b_); \
SWAP = *a; \
*a = *b; \
*b = SWAP; \
} while (0)
also: Macro SWAP(t,x,y) exchanging two arguments of type t
Is it possible to implement this functionality while being...
- portable (no compiler specific
typeof
) - without using function calls such as
memcpy
(which isn't assured to get optimized out, it wasn't in my tests at least)
I came up with a flawed method which uses a struct, defined to be the size of the input.
#define SWAP(a_, b_) do \
{ \
struct { \
char dummy_data[sizeof(a_)]; \
} SWAP, *a = (void *)(&(a_)), *b = (void *)(&(b_)); \
/* ensure sizes match */ \
{ char t[(sizeof(a_) == sizeof(*a)) ? 1 : -1]; (void)t; } \
/* check types are compatible */ \
(void)(0 ? (&(a_) == &(b_)) : 0); \
SWAP = *a; \
*a = *b; \
*b = SWAP; \
} while (0)
... but it can fail if the temporary struct
gets padded by the compiler (Depending on GCC's __packed__
would work but then its no longer portable)
It also may have issue with alignment depending on the architecture.