一般答案:
#define swap(x,y) x = x + y; y = x - y; x = x - y;
但是在以下情况会出错!
if( x > y)
{
swap( x , y );
}
else
x++;
展开后y = x - y; x = x - y;将不会执行
所以比较好的写法是:
#define swap(x,y) do{x = x + y; y = x - y; x = x - y;}while(0)
#define swap(x,y) x = x + y; y = x - y; x = x - y;
但是在以下情况会出错!
if( x > y)
{
swap( x , y );
}
else
x++;
展开后y = x - y; x = x - y;将不会执行
所以比较好的写法是:
#define swap(x,y) do{x = x + y; y = x - y; x = x - y;}while(0)