Wednesday, February 24, 2010

multi-statement macros - A Coding practise

This is an interesting topic about Macro Usage

I have a macro

#define SWAP(X,Y) { X = X+ Y; Y = X - Y; X = X - Y; }

So, The above macro swaps two numbers.

I can use

int x = 5, y =4;
SWAP(x,y);

Works perfect.

Now I will use the same as

if ( x > 0)
SWAP(X,Y);

The above one also works fine.

Now
if ( x > 0)
SWAP (x,y);
else
printf("\n X is Below Zero");

So..will the above works.

Noooo..
Before getting solution let us understand the problem my expanding:

if (x > 0)
{
x =x + y;
y = x - y;
x = x -y;
};
else
printf("\n X is Below Zero");

If we compile the above we will get the error like "
 "ERROR!!! "parse error before else"
Because of the extra semi-colon before Else.


So, the solution is embed the multi-staement macro between do-while(0) loop :)

So, the macro defination would be

#define SWAP(X,Y) \
do { \
X = X+ Y; \
Y = X - Y; \
X = X - Y; \
}while (0)

Thats it..

This is the safest way of using multi-statemetn macros ..

OR
There is another Simple way which is bruit-forcing a coding standard for coders ...and here is the rule:

Never forget to use parenthesis even the functional block has one statement
that means

instead of using
if (x > 0)
SWAP (x,y);
else
printf("\n X is Below Zero");

we should use :
if (x > 0)
{
SWAP(x,y);
}
else
{
printf("\n X is Below Zero");
}

1 comment: