John Matthews wrote:
> --- In [email protected], WLJiang WLJiang <iamwlji...@...> wrote:
>> O,the right is #define swap(a,b) {temp=a; a=b; b=temp;}
> 
> No it isn't - see previous posts.

I don't know why people are discussing a macro to swap two variables. 
Macros are hard to write, bug-prone, hard to figure out why they fail to 
compile at compile-time, and debuggers generally can't follow into them. 
  In short, they are a pain to write, use, and maintain.

http://c-faq.com/cpp/swapmacro.html

The only right answer is to use a function - you can use the 'inline' 
keyword to get the compiler to consider inlining it:

inline void swap_int(int *a, int *b)
{
   int temp = *a;
   *a = *b;
   *b = temp;
}

swap_int(&a, &b);


But this approach restricts you to 'int'.  In C++, you have std::swap() 
- an inlined template function capable of handling any data type.  If 
you want a general-purpose approach that follows good design, your ONLY 
choice is to switch to C++.

IF you feel you still have to use a macro, it should look more like this:

#define my_swap(x, y, swap_type)  do { swap_type temp = (x);  (x) = (y); 
  (y) = temp; } while(0)

my_swap(a, b, int);


That way you don't have to define a temporary prior to calling it (or 
use a single name for the temporary), the macro name doesn't potentially 
conflict with any future use of std::swap(), all the variables are 
correctly parenthesis-wrapped (a good habit to have when authoring 
macros), and it follows the typical practice of using do...while(0). 
Still, I highly discourage this in favor of functions!  Or simply switch 
to C++ and use std::swap().  Reserve macros for when it truly is 
necessary and consider them an advanced topic.  You will end up with 
much cleaner, easier to debug code as a result.

-- 
Thomas Hruska
CubicleSoft President
Ph: 517-803-4197

*NEW* MyTaskFocus 1.1
Get on task.  Stay on task.

http://www.CubicleSoft.com/MyTaskFocus/

Reply via email to