C Program To Swap Two Variables

Swapping two variables is one of the most common operations in sorting, data structure manipulation, and algorithm implementation. There are three standard methods: using a temporary variable (clearest), arithmetic (no temp, but overflow risk), and XOR bit manipulation (no temp, no overflow, but tricky for same-variable self-swap). All three produce the same result — understanding the tradeoffs matters.

The original post mentioned the XOR method but only showed that code, without comparing the three approaches. This rewrite presents all three in a single compilable program using pointer parameters.

C Program: Swap Two Variables — Three Methods

/* Swap two variables: three methods
 *   1. Using a temporary variable (recommended)
 *   2. Using arithmetic (addition-subtraction)
 *   3. Using XOR bit manipulation
 * Compile: gcc -ansi -Wall -Wextra swap.c -o swap */
#include <stdio.h>

void swap_temp(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

void swap_arith(int *a, int *b)
{
    *a = *a + *b;
    *b = *a - *b;
    *a = *a - *b;
}

void swap_xor(int *a, int *b)
{
    *a ^= *b;
    *b ^= *a;
    *a ^= *b;
}

int main(void)
{
    int x, y;
    printf("Enter two integers: ");
    if (scanf("%d %d", &x, &y) != 2) {
        printf("Invalid input.\n");
        return 1;
    }

    printf("\nMethod 1 — Temp variable:\n");
    printf("  Before: x=%d, y=%d\n", x, y);
    swap_temp(&x, &y);
    printf("  After:  x=%d, y=%d\n", x, y);
    swap_temp(&x, &y);  /* restore */

    printf("\nMethod 2 — Arithmetic:\n");
    printf("  Before: x=%d, y=%d\n", x, y);
    swap_arith(&x, &y);
    printf("  After:  x=%d, y=%d\n", x, y);
    swap_arith(&x, &y);  /* restore */

    printf("\nMethod 3 — XOR:\n");
    printf("  Before: x=%d, y=%d\n", x, y);
    swap_xor(&x, &y);
    printf("  After:  x=%d, y=%d\n", x, y);

    return 0;
}

How to Compile and Run

gcc -ansi -Wall -Wextra swap.c -o swap
./swap

Sample Output

Enter two integers: 10 20

Method 1 — Temp variable:
  Before: x=10, y=20
  After:  x=20, y=10

Method 2 — Arithmetic:
  Before: x=10, y=20
  After:  x=20, y=10

Method 3 — XOR:
  Before: x=10, y=20
  After:  x=20, y=10

Step-by-Step Trace — Arithmetic Method (a=10, b=20)

Step Statement a b
Start 10 20
1 a = a + b 30 20
2 b = a – b 30 10
3 a = a – b 20 10

Step-by-Step Trace — XOR Method (a=10=1010₂, b=20=10100₂)

Step Statement a (binary) b (binary)
Start 01010 10100
1 a ^= b 11110 10100
2 b ^= a 11110 01010
3 a ^= b 10100 01010
Result 20 10

Comparison of the Three Methods

Method Extra memory Overflow risk Self-swap (a==b pointer)? Use
Temp variable 1 extra var None Safe Recommended always
Arithmetic None Yes (int overflow) Safe Avoid for large values
XOR None None Broken if same pointer Interview curiosity, not production

The XOR Self-Swap Bug Explained

If you call swap_xor(&x, &x) (same variable both arguments), the XOR method silently zeroes out x:

  • Step 1: x ^= x → x = 0 (any value XOR itself = 0)
  • Step 2: x ^= x → x = 0 (still 0)
  • Step 3: x ^= x → x = 0 (x is now destroyed)

The temp variable method handles this correctly: temp = x = original value, then x = x = same value — no corruption. In practice, sorting algorithms call swap when two indices might be the same, so always use the temp method in production code.

Why Pass Pointers?

In C, all arguments are passed by value. If you write void swap(int a, int b) { ... } and modify a and b inside the function, the caller’s variables are unchanged — the function only swaps local copies. To modify the caller’s variables, pass their addresses (&x, &y) and use pointer dereference (*a, *b) inside the function.

What This Program Teaches

  • Always use the temp variable method — it is the only method that is safe for all types (floats, structs, any size), all values, and self-swaps. The “no temp” tricks are interview questions, not best practice.
  • Pass-by-pointer for output parameters — this is the fundamental C pattern for functions that must modify the caller’s data. Swap, min-max, read-two-values, etc. all use this pattern. It is the C equivalent of pass-by-reference in C++.
  • Integer overflow in arithmetic swap — for int values near INT_MAX, adding two large values overflows, giving wrong results or undefined behavior. The temp method never overflows because it just copies values, not computes with them.

Related Programs

Recommended book:
The C Programming Language — Kernighan & Ritchie (India) |
(US)
 | 
C Programming: A Modern Approach — K.N. King (India) |
(US)

Practice what you learned: C Aptitude Questions — or try our C Programming Quiz App on Android.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>