C - Swap two numbers without using Temporary Variable

The value of two variables can be swapped without using any temporary variables. The method involves using operators like +, *, / and bitwise.

Method 1: Using + operator

In the example below, the + operator is used to swap the value of two variables x and y.

#include <stdio.h>

static void swap(int, int);

static void swap(int x, int y) {
printf("Before Swap.\n");
printf("x = %i\n", x);
printf("y = %i\n", y);

//Swap technique
x = x + y;
y = x - y;
x = x - y;

printf("After Swap.\n");
printf("x = %i\n", x);
printf("y = %i\n", y);
}

int main() {
swap(10, 25);
}

The above code will give the following output:

Before Swap.
x = 10
y = 25
After Swap.
x = 25
y = 10

Method 2: Using * operator

Like + operator, the * operator can also be used to swap the value of two variables x and y.

#include <stdio.h>

static void swap(int, int);

static void swap(int x, int y) {
printf("Before Swap.\n");
printf("x = %i\n", x);
printf("y = %i\n", y);

//Swap technique
x = x * y;
y = x / y;
x = x / y;

printf("After Swap.\n");
printf("x = %i\n", x);
printf("y = %i\n", y);
}

int main() {
swap(10, 25);
}

The above code will give the following output:

Before Swap.
x = 10
y = 25
After Swap.
x = 25
y = 10

Method 3: Using / operator

Similarly / operator can also be used to swap the value of two variables x and y.

#include <stdio.h>

static void swap(float, float);

static void swap(float x, float y) {
printf("Before Swap.\n");
printf("x = %f\n", x);
printf("y = %f\n", y);

//Swap technique
x = x / y;
y = x * y;
x = y / x;

printf("After Swap.\n");
printf("x = %f\n", x);
printf("y = %f\n", y);
}

int main() {
swap(10, 25);
}

The above code will give the following output:

Before Swap.
x = 10.000000
y = 25.000000
After Swap.
x = 25.000000
y = 10.000000

Method 4: Using bitwise operator

The bitwise XOR (^) operator can also be used to swap the value of two variables x and y. It returns 1 when one of two bits at same position in both operands is 1, otherwise returns 0.

#include <stdio.h>

static void swap(int, int);

static void swap(int x, int y) {
printf("Before Swap.\n");
printf("x = %i\n", x);
printf("y = %i\n", y);

//Swap technique
x = x ^ y;
y = x ^ y;
x = x ^ y;

printf("After Swap.\n");
printf("x = %i\n", x);
printf("y = %i\n", y);
}

int main() {
swap(10, 25);
}

The above code will give the following output:

Before Swap.
x = 10
y = 25
After Swap.
x = 25
y = 10