`void f(int *a, int *b)
{
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
}`
this code has no local variables and two int parameters
`void f(int *a, int *b)
{
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
}`
this code has no local variables and two int parameters
The code is used to swap two numbers. See the code :
#include<stdio.h>
void f(int *a, int *b)
{
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
}
int main()
{
int a = 9, b = 4;
f(&a,&b);
printf("Value of a is %d \n", a);
printf("Value of b is %d",b);
}
The output is :
Value of a is 4
Value of b is 9
It swaps the values of a
and b
. This is exploiting the properties of XOR that:
a ^ a == 0
a ^ 0 == a
So, in your code, first you replace a
with a^b
on line 1.
Then, on line 2 you do: (a ^ b) ^ b == a ^ (b ^ b) == a ^ 0 == a
, and assign that to b
. So, at this point b
has the old value of a
.
On line 3 you do the same thing as above, except this time the a
s get cancelled out, and you're left with the old value of b
, which is then assigned to a
How do you save space using XOR in C?
Write code that does not fail with select values.
Write clear code that the compiler can readily optimize and then enable those optimizations. Possible use inline
. With inline
and your compiler does not optimize this well, get a better compiler.
/* inline */ void f(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
What does the code below do?
OP's code fails with f(&a, &b);
when a,b
point to the same place as it zeros out data.
Do not use.
Faulty tricks like the exclusive OR swap belong to an earlier era of weak compilers.