Friday, November 27, 2009

Swapping 2 variables using macro

Problem

How to swap 2 variables using macro?

 Solution

 #define swap(type,a,b) type temp;temp=a;a=b;b=temp;

Now, think what happens if you pass in something like this

 swap(int,temp,a) //You have a variable called "temp" (which is quite possible).


This is how it gets replaced by the macro
int temp;
temp=temp;
temp=b;
b=temp;

0 comments:

Post a Comment