This month’s Exercise challenges you to swap two variables’ values without using a third variable. It’s a solution widely available on the Internet, but your job is to figure out the technique without looking elsewhere.
I confess that I saw this solution months ago and marveled at it. But I forgot the specifics. Rather than look it up again, I set out to devise it on my own, using only my vague memory of the mathematical operations used on the two variables to swap values. Here are the three statements I use:
b = b + a;
a = b - a;
b = b - a;
Yes, it took me a while to hone this result, which works for both signed and unsigned values. Figure 1 helps illustrate how the operation works.
Effectively, variable b
becomes what would otherwise be swapping variable c
. First it holds the sum of a
and b
: b = b + a
When original a
is subtracted, what’s left over is b
, which is assigned to a
: a = b - a
Finally, the new value of a
(original b
) is subtracted from new b
, which yields the original value of a
, assigned to b
: b = b - a
It took my brain a few minutes to accept this solution. I even tried to condense it to only two statements, but either I’m not that smart or such a solution isn’t possible. Regardless, here is the full solution:
2023_06-Exercise.c
#include <stdio.h>
int main()
{
int a,b;
printf("Enter value A: ");
scanf("%d",&a);
printf("Enter value B: ");
scanf("%d",&b);
printf("Before: A=%d, B=%d\n",a,b);
/* swap variables */
b = b + a;
a = b - a;
b = b - a;
printf("After: A=%d, B=%d\n",a,b);
return(0);
}
After writing this code, I checked the interwebs to see what I found earlier, the inspiration for this Exercise. Yep, I got it right. I hope you did as well.
I assumed you were referring to using exclusive or rather than addition and subtraction. I think it should be possible to condence the +/- method into one line.
I grew too lazy to try. But I do admire your XOR solution.