Swap Two Numbers in C: 3 Methods

In C language, there are three methods to swap the values of two numbers.

Option 1: Utilize a third variable.

void swap(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

Option 2: Utilizing addition and subtraction.

void swap(int* a, int* b) {
    *a = *a + *b;
    *b = *a - *b;
    *a = *a - *b;
}

Option Three: Utilizing the XOR operation.

void swap(int* a, int* b) {
    *a = *a ^ *b;
    *b = *a ^ *b;
    *a = *a ^ *b;
}

All three methods can achieve swapping the values of two numbers, but the third method using XOR operation is relatively more efficient.

bannerAds