   # Swap value two variables without using third variable or +/- operator?

106 views

How can I wwap value two variables without using third variable or +/- operator? posted Jul 4, 2014

We can use the XOR.

x = x XOR y
y = x XOR y
x = x XOR y answer Jul 4, 2014

Use bitwise XOR somethign like

`````` int x = 1, y = 2;

x = x ^ y;  // x now becomes 3(0011)
y = x ^ y;  // y becomes 2 (0010)
x = x ^ y;  // x becomes 1 (0001)
``````

Or use * and / operation

``````int x = 1, y = 20;

x = x * y;  // x now becomes 20
y = x / y;  // y becomes 1
x = x / y;  // x becomes 20
`````` answer Jul 4, 2014
In case of 0 and other value your logic will fail dear
``````#include <stdio.h>
void swap(int *xp, int *yp)
{
*xp = *xp ^ *yp;
*yp = *xp ^ *yp;
*xp = *xp ^ *yp;
}

int main()
{
int x = 10, y = 5;
swap(&x, &y);
printf("After swap(&x, &y): x = %d, y=%d", x, y);
return 0;
}
`````` answer Mar 10, 2016
Similar Questions

a and b are compared against
the threshold ‘TH’, and the nearest value is voted as output

I have a recursive function as below,

``````void func()
{
if(counter>10)
return;
func();
}
``````

Here, I need to come out of the function when counter reaches specific number(10 as per example).
Now, the condition is, I can't take this counter as global or static or can't pass this counter as parameter.

Any suggestion to solve this given above terms.