Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/articles/c-tutorials/)
-   -   Swap two variables using macro (http://www.go4expert.com/articles/swap-variables-using-macro-t1732/)

 Ziaur Rahman 26Oct2006 18:42

Swap two variables using macro

The code to swap two variables using macro expansions

Code: C

`#include<stdio.h>#include<conio.h>#define SWAPE(x,y) int t;t=x;x=y;y=t;main(){    int a,b;        printf("\n Enter two number");    scanf("%d%d",&a,&b);    printf("\n Before swaping the Value of a=%d and b=%d",a,b);    SWAPE(a,b);    printf("\n After swap value of a=%d and b=%d",a,b);    return 0;}`

 nicenaidu 2Nov2006 13:35

Swap two numbers without using temp variable

//Code for swapping two numbers without using temp variable
Code: CPP

`#include <iostream>using namespace std;int main (){  int a = 10;  int b = 5;  cout << "before swap: a = " << a << " b = " << b << endl;    //Swapping numbers without using a temp var : method1  a = a ^ b;  b = b ^ a;  a = a ^ b;  cout << "after swap using method1: a = " << a << " b = " << b << endl;  //Swapping numbers without using a temp var : method2  a = a + b;  b = a - b;  a = a - b;  cout << "after swap using method2: a = " << a << " b = " << b << endl;  return 0;}`

 aurnk 22Dec2006 14:42

Re: Swap two variables using macro

better method is
usage of
#define swap(a,b) a^=b^=a^=b;

 aurnk 22Dec2006 14:43

Re: Swap two variables using macro

better method is
usage of
#define swap(a,b) a^=b^=a^=b;

one line swap without using temporary variable.

 Peter_APIIT 12Apr2007 11:15

Re: Swap two variables using macro

Hello nicenaidu, i have compiler the file you post in MS VS 2005 but the IDE complaint that cstiod.h error .

Your help is greatly appreciated by me and others.

 Vikrant Singh 24May2007 15:43

Re: Swap two variables using macro

Here is a suggestion...

Using ^ operator is not the best way of swapping two values.
Just consider is soemone try to SWAP same variable, like SWAP(A,A) what will happen?
A^A will clear the all of the bits of A, because of which A will lost its original value on calling SWAP macro.

Further swapping value using equation like A+B is not advisable , if A and B are very large values than result of this addition may cross the maximum value which an integer can store. We may end up with a incorrect result.

So we should not try to play smart with fancy instruction as far as swapping is concerned.

 oleber 25May2007 13:30

Re: Swap two variables using macro

Lets speak of C/C++

Why use a Macro and fix a type?

Template functions can do the work cleaner.

Code: CPP

`template <class TYPE>void swamp(TYPE &var1, TYPE &var2) {    TYPE var_temp = var1;    var1 = var2;    var2 = var_temp;}`

 Vikrant Singh 25May2007 18:59

Re: Swap two variables using macro

This can be done in Macro also…
Try this…
#define SWAP (A, B) struct tempStruct { char C[sizeof(A)];} swap_tmp;\
swap_tmp = *( struct tempStruct*) &A;\
*( struct tempStruct*) &A = *( struct tempStruct*) &B;\
*( struct tempStruct*) &B = swap_tmp;

 oleber 25May2007 20:04

Re: Swap two variables using macro

Correct to :p

Code:

```    #define SWAP(A, B) {struct tempStruct { char C[sizeof(A)];} swap_tmp;\     swap_tmp = *( struct tempStruct*) &A;\     *( struct tempStruct*) &A = *( struct tempStruct*) &B;\     *( struct tempStruct*) &B = swap_tmp;}```
Other wise you get problems when using diferent types

Code: CPP

`#include <cstdio>    #include <iostream>        using namespace std;        #define SWAP(A, B) {struct tempStruct { char C[sizeof(A)];} swap_tmp;\    swap_tmp = *( struct tempStruct*) &A;\    *( struct tempStruct*) &A = *( struct tempStruct*) &B;\    *( struct tempStruct*) &B = swap_tmp;}        int main () {                char v1 = 'a';        char v2 = 'b';            SWAP (v1, v2);        cout << v1 << "   " << v2 <<"\n";            float f1 = 45;        float f2 = 123;        SWAP (f1, f2);        cout << f1 << "   " << f2 <<"\n";    }`

 keith12125 4Jul2007 15:39

Re: Swap two variables using macro

>better method is
>usage of
>#define swap(a,b) a^=b^=a^=b;
>
>one line swap without using temporary variable

what exactly does the assignment operator ^= do?

 Vikrant Singh 4Jul2007 15:43

Re: Swap two variables using macro

a^=b is equivalent to a = a ^ b

 keith12125 5Jul2007 15:51

Re: Swap two variables using macro

^= is a binary XOR assignment;

It seems to run really slow however...
I wrote 2 versions of the same sorting function, 1 using a temp variable and the other using this method. When i ran it on my P4 sort_xor took 24 seconds while sort_temp took 15.

Code:

```#include <stdio.h> #include <stdlib.h> #define SIZE 50000 void sort_xor(int *a, int size) /* Sorts the terms of the given array into numerical order. */ {         bool stop = false;         while (!stop)         {                 stop = true;                 for(int i = 0; i < size - 1; i++)                         if (a[i] > a[i + 1])                         {                                 a[i] ^= a[i + 1] ^= a[i] ^= a[i + 1];                                 stop = false;                         }         } } void sort_temp(int *a, int size) /* Sorts the terms of the given array into numerical order. */ {         bool stop = false;         int temp;         while (!stop)         {                 stop = true;                 for(int i = 0; i < size - 1; i++)                         if (a[i] > a[i + 1])                         {                                 temp = a[i];                                 a[i] = a[i + 1];                                 a[i + 1] = temp;                                 stop = false;                         }         } } int main() {         int a[SIZE];         for (int i = 0; i < SIZE; i++)                 a[i] = SIZE - i;         printf("Sorting with sort_xor...\n");                    /* I start timing here*/         sort_xor(a, SIZE);         printf("Finished Shorting with shor_xor.\n");            /* Stop here */         printf("Press any key to sort with sort_temp\n");         getchar();         for (int i = 0; i < SIZE; i++)                 a[i] = SIZE - i;         printf("Sorting with sort_temp...\n");                  /* I start timing here*/         sort_temp(a, SIZE);         printf("Finished Shorting with shor_temp.\n");          /* Stop here */ }```

 Vikrant Singh 5Jul2007 18:26

Re: Swap two variables using macro

Yes you are correct. and following is the reason...

analyze following assembly code

temp = x
mov eax,dword ptr [x]
mov dword ptr [temp],eax

x = y;
mov eax,dword ptr [y]
mov dword ptr [x],eax

y = temp;
mov eax,dword ptr [temp]
mov dword ptr [y],eax

6 mov instruction....

x ^= y ^= x ^= y;
mov eax,dword ptr [x]
xor eax,dword ptr [y]
mov dword ptr [x],eax
mov ecx,dword ptr [y]
xor ecx,dword ptr [x]
mov dword ptr [y],ecx
mov edx,dword ptr [x]
xor edx,dword ptr [y]
mov dword ptr [x],edx
6 Mov + 3 Xor

 sharma_atul13 16Jul2007 15:34

Re: Swap two variables using macro

the below logic also works as follows for swapping of nos without external variable introduction
Code:

```main() {   int a,b;   printf("enter the nos");   scanf("%d %d",&a,&b);   printf("nos before swapping a=%d ,b=%d", a,b);   a=a*b;   b=a/b;   a=a/b;   printf("nos after swapping  a=%d ,b=%d", a,b); }```

 All times are GMT +5.5. The time now is 09:45.