Swap two variables using macro

Discussion in 'C' started by Ziaur Rahman, Oct 26, 2006.

  1. Ziaur Rahman

    Ziaur Rahman New Member

    Joined:
    Oct 22, 2006
    Messages:
    11
    Likes Received:
    1
    Trophy Points:
    0
    Occupation:
    Student
    Location:
    Pune
    The code to swap two variables using macro expansions

    Code:
    #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;
    }
     
  2. nicenaidu

    nicenaidu New Member

    Joined:
    Nov 2, 2006
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Swap two numbers without using temp variable

    //Code for swapping two numbers without using temp variable
    Code:
    #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;
    }
     
  3. aurnk

    aurnk New Member

    Joined:
    Dec 13, 2006
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    better method is
    usage of
    #define swap(a,b) a^=b^=a^=b;
     
  4. aurnk

    aurnk New Member

    Joined:
    Dec 13, 2006
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    better method is
    usage of
    #define swap(a,b) a^=b^=a^=b;

    one line swap without using temporary variable.
     
  5. Peter_APIIT

    Peter_APIIT New Member

    Joined:
    Apr 11, 2007
    Messages:
    92
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Student
    Location:
    Malaysia
    Hello nicenaidu, i have compiler the file you post in MS VS 2005 but the IDE complaint that cstiod.h error .

    Thanks for your help.


    Your help is greatly appreciated by me and others.
     
  6. Vikrant Singh

    Vikrant Singh New Member

    Joined:
    May 24, 2007
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    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.
     
  7. oleber

    oleber New Member

    Joined:
    Apr 23, 2007
    Messages:
    37
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    Software Developer (Perl, C/C++ and Java)
    Location:
    Hamburg, Germany
    Home Page:
    http://oleber.freehostia.com/
    Lets speak of C/C++

    Why use a Macro and fix a type?

    Template functions can do the work cleaner.

    Code:
    template <class TYPE>
    void swamp(TYPE &var1, TYPE &var2) {
    	TYPE var_temp = var1;
    	var1 = var2;
    	var2 = var_temp;
    }
    
     
  8. Vikrant Singh

    Vikrant Singh New Member

    Joined:
    May 24, 2007
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    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;
     
  9. oleber

    oleber New Member

    Joined:
    Apr 23, 2007
    Messages:
    37
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    Software Developer (Perl, C/C++ and Java)
    Location:
    Hamburg, Germany
    Home Page:
    http://oleber.freehostia.com/
    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:
        #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";
        }
        
     
    Last edited: May 25, 2007
  10. keith12125

    keith12125 New Member

    Joined:
    Jul 4, 2007
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    >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?
     
  11. Vikrant Singh

    Vikrant Singh New Member

    Joined:
    May 24, 2007
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    a^=b is equivalent to a = a ^ b
     
  12. keith12125

    keith12125 New Member

    Joined:
    Jul 4, 2007
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    I answered my own question...
    ^= 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 */
    }
     
  13. Vikrant Singh

    Vikrant Singh New Member

    Joined:
    May 24, 2007
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    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
     
  14. sharma_atul13

    sharma_atul13 New Member

    Joined:
    Jul 16, 2007
    Messages:
    7
    Likes Received:
    0
    Trophy Points:
    0
    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);
    }
     
    Last edited by a moderator: Jul 16, 2007

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice