close

Reference Link : http://offclassroom.com/off-classroom/cc/282-swap-variables-in-c-without-using-temporary-variable.html


Hello friends! Being a final year computer engineering student, I have gone through so many C programming logics as a preparation of Interview (unfortunately still haven't got a chance to face it :-)
Recently one of my friends cleared the first two rounds of aptitude & programming and then got a chance to face the interview. He was asked so many logical questions on C & C++ . One of those question was, “How many different methods do you know to swap two variables without using a temporary variable?”

From this question, we can't give a particular answer as there might be so many logical solutions that can be used to swap two variables. I certainly know three:

Method 1: Swap two variables using + & - operators

a = a+b;
b = a-b; 
a = a-b;

lets take a=10 & b=5,

a =  a+b = 10+5 = 15      so, a=15 & b=5
b = a-b = 15-5 = 10        so, a=15 & b=10
a = a-b = 15-10 = 5       so, a=5 & b=10

Thus a=5 & b=10, values are swapped.
This is the most popular method for swapping two variables but still this method has one drawback. If a and b are big and their addition is bigger than the size of integer than this might end up giving you wrong results.

Method 2 : Using X-OR (^) operator

a = a^b;
b = b^a;
a = a^b;

lets take a same example a=10 & b=5,

a = a^b = 10^5 = 15        so, a=15 & b=5
b = b^a = 5^15 = 10        so, a=15 & b=10
a = a^b =15^10 = 5         so, a=5 & b=10

Drawback of this method is that it will not work for floating-point values.

Method 3 : Using Pointers

We can overcome the drawback of Method 2 if we use pointers.

swap(int *a, int *b) 

*a = *a^*b;
*b = *b^*a;
*a = *a^*b;
}

We still have some problem with this method if use X-OR (^)
Now suppose, by mistake, your code passes the pointer to the same variable to this function. Since Xor'ing an element with itself sets the variable to zero, this routine will end up setting the variable to zero (ideally it should have swapped the variable with itself). 
One solution to this problem is to check if the numbers to be swapped are already equal to each other.

swap(int *a, int *b) 

if(*a!=*b) 

*a = *a^*b;
*b = *b^*a;
*a = *a^*b;

}

arrow
arrow
    全站熱搜

    techdrew 發表在 痞客邦 留言(0) 人氣()