Vikrant Singh's Avatar, Join Date: May 2007
Newbie Member
a^=b is equivalent to a = a ^ b
keith12125's Avatar, Join Date: Jul 2007
Newbie Member
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 */
}
Vikrant Singh's Avatar, Join Date: May 2007
Newbie Member
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's Avatar, Join Date: Jul 2007
Light Poster
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 shabbir; 16Jul2007 at 20:17.. Reason: Code block