Q:

Swap two numbers without using a temporary variable?

0

Swap two numbers without using a temporary variable?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Using the EX-OR operator, we can swap two numbers. Here the concept is that EX-OR of two same numbers is zero.

#include <stdio.h>
void SwapTwoNumber(int *a, int *b)
{
    if(*a == *b) // Check if the two addresses are same
        return;
    *a = *a ^ *b;
    *b = *a ^ *b;
    *a = *a ^ *b;
}
int main()
{
    int x = 10;
    int y = 20;
    SwapTwoNumber(&x, &y);
    printf("x = %d and y = %d",x,y);
    return 0;
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Clear all bits from MSB to the ith bit... >>
<< Compute the minimum (min) or maximum (max) of two ...