Swap value of two variables without using a third, using either sum or subtraction only

Asked

Viewed 688 times

0

Using only two variables (A and B) and also using only (sum or subtraction), make the value of A turn the value of B and the value of B become the value of A.

1 answer

2

Can it be using the operator or-exclusive? If yes:

#include <stdio.h>

int main() {
    int a = 123;
    int b = 456;
    printf("%d %d\n", a, b);
    a ^= b;
    b ^= a;
    a ^= b;
    printf("%d %d\n", a, b);
    return 0;
}

Here’s the way out:

123 456
456 123

See here working on ideone.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.