摘要:[C/C++] Swap two integer variables using Macro
以下紀錄一些利用Macro手段達到SWAP變數的技巧:
#define SWAP(x, y) \
int tmp = x;\
x = y;\
y = tmp;
也可以縮成一行(但是可讀性就變差了)
#define SWAP(x, y) int tmp = x; x = y; y = tmp;
Horowitz的Fundamentals of Data Structures in C一書中使用的:
#define SWAP(x, y, t) ((t) = (x), (x) = (y), (y) = (t))
比較General的方法(do/while (0) 是為了將Macro的內容打包起來):
#define swap(x,y) do \
{ unsigned char swap_temp[sizeof(x) == sizeof(y) ? (signed)sizeof(x) : -1]; \
memcpy(swap_temp,&y,sizeof(x)); \
memcpy(&y,&x, sizeof(x)); \
memcpy(&x,swap_temp,sizeof(x)); \
} while(0)
GCC-specific extension:
#define SWAP(x, y) do { typeof(x) temp##x##y = x; x = y; y = temp##x##y; } while (0)