Swap two integers using a temporary variable, arithmetic, and XOR, and say which is best.
Solution
main.c
#include <stdio.h>
int main(void) {
int a = 3, b = 8;
int t = a; /* 1. temporary variable: clear and always correct */
a = b;
b = t;
printf("temp: a=%d b=%d\n", a, b);
a = a + b; /* 2. arithmetic: can overflow */
b = a - b;
a = a - b;
printf("arith: a=%d b=%d\n", a, b);
a ^= b; /* 3. XOR: fails if a and b are the same variable */
b ^= a;
a ^= b;
printf("xor: a=%d b=%d\n", a, b);
return 0;
}
Output Verified by compiling and running
temp: a=8 b=3
arith: a=3 b=8
xor: a=8 b=3
Each method swaps the values (so they alternate back and forth). Use the temporary: it never overflows, works for any type, and compilers generate the same fast code.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!