C program to swap two integers without using third variable
#include <stdio.h> | |
void main() { | |
int a, b; | |
printf("Enter two integer values for swapping : "); | |
scanf("%d %d", &a, &b); | |
printf("A = %d, B = %d\n", a, b); | |
a = a + b; | |
b = a - b; | |
a = a - b; | |
printf("After swapping :\n"); | |
printf("A = %d \t, B = %d\n", a, b); | |
printf("===End===\n"); | |
} |
Top comments (4)
While it does have some educational value to show that this is possible, this method has two issues:
Both
a = a + b
anda = a - b
can cause an overflow.I can't imagine many situations where saving a few bytes really makes up for the loss in readability.
It also works with XOR (avoiding the overflow problem):
Agreed, this is definitely the way to do it.
reduced to one line:
a ^= b ^= a ^= b;