LearnFrenzy
Sign in Take a free test

C Variables · Variable Programs · Question 4

Swap two variables in three ways in C Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links