Sunday, August 7, 2011

A do while in a Macro

Looks like I know very little of C. So I never thought I would ever need to use a do while loop in a Macro.

Now consider this. A typical swap function looks like following:
  1: template void swap(T& a, T& b){
  2:   T tmp;
  3:   tmp = a;
  4:   a = b;
  5:   b = a;
  6: }

As you can see that there are three different things on which the function depends, the type T and the variables a and b. How can I write a C Macro which does exactly the same thing?

  1: #define FFSWAP(T,a,b) do{T SWAP_tmp= b; b= a; a= SWAP_tmp;}while(0)

This is taken liberally from common.h in FFmpeg source code.

So we are writing a do,while loop which runs exactly once. Inside the loop we have a temporary variable created of type T (we choose a name for the temporary variable which is not expected to be taken by other variables inside the function). And rest is essentially the same 3 statements to achieve swapping.I still don't fully understand why did we need to add the do/while with this Macro. It might work without do/while also.

Please note that I don't want to say that macros are better than function templates. I just want to say that, I never knew about this macro magic.

No comments: