-4

Here I have tried to make a function which may swap two values without a third variable. What other implementation might work to do so other than the one stated below?

void swap(int* x, int* y)
{
    (*x)=(*x)+(*y);
    (*y)=(*x)-(*y);
    (*x)=(*x)-(*y);

}
Priyanka
  • 20
  • 4

2 Answers2

3

It looks like you are trying to do the XOR swap trick?

#include <stdio.h>

void swap(int* x, int* y)
{
    *x^=*y;
    *y^=*x;
    *x^=*y;
}
int main(){
    int x = 1;
    int y = 2;
    swap(&x, &y);
    printf("x = %d, y =%d\n", x, y);
}
merlin2011
  • 71,677
  • 44
  • 195
  • 329
0

it should work actually...

I used the following code with your function:

void swap(int* x, int* y)
{
  (*x)=(*x)+(*y);
  (*y)=(*x)-(*y);
  (*x)=(*x)-(*y);
}

int a1=1;
int a2=2;

main()
{
   swap(&a1,&a2);

   printf("a1= %d\na2= %d \n",a1 ,a2);
}
  • I had tried using the same code earlier but it didn't work well at that time but now it works fines. May be it was some interpreter etc issue. @Oli Charlesworth sorry for the inconvenience. – Priyanka Jun 22 '14 at 14:19