0
`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

Gerhardh
  • 11,688
  • 4
  • 17
  • 39
  • it is swapping variables – kelvin Nov 21 '20 at 11:34
  • thank youu for answering –  Nov 21 '20 at 11:42
  • 2
    Rolled back your edit. Please do not vandalize your question by removing all the content. StackOverflow is not a personal support size but a Q&A site where post shall help other people as well. – Gerhardh Nov 21 '20 at 12:48
  • *How do you save space using XOR in C?* You **DON'T**. The code in your question is an absolutely horrible way to swap variables - it's only going to save space on a system that doesn't use registers. Step through a swap using registers: load value from X into r1, load value from Y into r2, save r1 to Y, save r2 to X. Note that any temporary variable **is not used**. Now do the step-by-step XOR. Instead of 4 steps, it's 12 - at least. XOR swapping is a **BAD IDEA**. If you're lucky, your compiler recognizes what you're doing and junks it. – Andrew Henle Nov 21 '20 at 17:32
  • And an XOR swap has the bonus feature of destroying your data by zeroing it out if `a` and `b` refer to the same location. **Don't do that**. – Andrew Henle Nov 21 '20 at 17:35

3 Answers3

1

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
Krishna Kanth Yenumula
  • 2,533
  • 2
  • 14
  • 26
1

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 as get cancelled out, and you're left with the old value of b, which is then assigned to a

Mustafa Quraish
  • 692
  • 4
  • 10
1

How do you save space using XOR in C?

  1. Write code that does not fail with select values.

  2. 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.

See How does XOR variable swapping work?.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256