I'm kind of new with these algorithms/techniques but I've had came up with this function;
function swap(int *p1, int *p2) {
*p1 = *p1 + *p2;
*p2 = *p1 - *p2;
*p1 = *p1 - *p2;
}
You can test this function like that;
int a = 10;
int b = 20;
printf("%d %d\n", a, b); // 10 20
swap(&a, &b);
printf("%d %d\n", a, b); // 20 10
Here's a 3-step explanation for better understanding;
*p1 = *p1 + *p2;
Add the values coming from p1 (*p1=10) and p2 (*p2=20) and store result on p1 (*p1=30).
*p2 = *p1 - *p2;
We know result of the addition, calculate the old value of p1 by subtracting current value of p2 (current *p2=20) from value coming from p1 (*p1=30) and store result on p2 (calculated *p2=10).
*p1 = *p1 - *p2;
Since the value of p1 (*p1=30) did not change on step 2 and we still have the old value of p1 on p2 (*p2=10), we can divide p2 into p1 and store the result on p1 (calculated *p1=20)
So as you can see we swapped two ints without defining any temporary variable and making pass-by-reference function call.
The reason of pass-by-reference is to minimize usage of memory. Because every pass-by-value call allocates new variables on the memory (to be deleted by GC or not) depends on how much parameter you've passed to the function.
void xorSwap (int **x, int **y) { if (x != y) { *x = (int*)((int)*x ^ (int)*y); *y = (int*)((int)*x ^ (int)*y); *x = (int*)((int)*x ^ (int)*y); } } int main(void){ int a = 7; int b = 11; int * pa = &b; int * pb = &b; printf("before %p %p / %d %d\n", pa, pb, *pa, *pb); xorSwap(&pa, &pb); printf("after %p %p / %d %d\n", pa, pb, *pa, *pb); return 0; }