Let's look at a simple example c to replace two numbers without using a third variable.
program 1:
#include<stdio.h>
Output:
Before replacing a = 10 b = 20 After replacing a = 20 b = 10
Program 2: Using * and /
Let's see another example to exchange two numbers with * and /.
#include<stdio.h>
Output:
Before replacing a = 10 b = 20 After replacing a = 20 b = 10
Program 3: Using the XOR Bitwise Operator:
The bitwise XOR operator can be used to replace two variables. XOR of two numbers x and y returns a number that has all bits as 1, where bits x and y are different. For example, XOR 10 (In Binary 1010) and 5 (In Binary 0101) are 1111, and XOR is 7 (0111) and 5 (0101) is (0010).
#include <stdio.h> int main() { int x = 10, y = 5; // Code to swap 'x' (1010) and 'y' (0101) x = x ^ y; // x now becomes 15 (1111) y = x ^ y; // y becomes 10 (1010) x = x ^ y; // x becomes 5 (0101) printf("After Swapping: x = %d, y = %d", x, y); return 0;
Output:
After replacing: x = 5, y = 10
Program 4:
No one suggested using std :: swap.
std::swap(a, b);
I do not use any temporary variables, and depending on the types a and b, the implementation may have a specialization that also does not. The implementation must be written, knowing whether the "trick" is suitable or not.
Problems with the above methods:
1) The approach based on multiplication and division does not work if one of the numbers is 0, when the product becomes 0 regardless of the other number.
2) Both arithmetic solutions can cause arithmetic overflow. If x and y are too large, addition and multiplication may fall outside the integer range.
3) When we use pointers to a variable and execute the swap function, all of the above methods fail when both pointers point to the same variable. Let's see what happens in this case, if both point to the same variable.
// XOR-based bit method
x = x ^ x; // x becomes 0 x = x ^ x; // x remains 0 x = x ^ x; // x remains 0
// Arithmetic method
x = x + x; // x becomes 2x x = x β x; // x becomes 0 x = x β x; // x remains 0
Let's look at the next program.
#include <stdio.h> void swap(int *xp, int *yp) { *xp = *xp ^ *yp; *yp = *xp ^ *yp; *xp = *xp ^ *yp; } int main() { int x = 10; swap(&x, &x); printf("After swap(&x, &x): x = %d", x); return 0; }
Exit
After replacing (& x, & x): x = 0
Switching a variable with itself may be required in many standard algorithms. For example, see This QuickSort implementation, where we can change the variable with ourselves. The above problem can be avoided by setting a condition before the replacement.
#include <stdio.h> void swap(int *xp, int *yp) { if (xp == yp) // Check if the two addresses are same return; *xp = *xp + *yp; *yp = *xp - *yp; *xp = *xp - *yp; } int main() { int x = 10; swap(&x, &x); printf("After swap(&x, &x): x = %d", x); return 0; }
Exit
After replacing (& x, & x): x = 10