📘 Lesson  ·  Lesson 61

Swap Without Third Variable

Why swap without a third variable?

Swapping two numbers means exchanging their values: if a is 5 and b is 9, after the swap a becomes 9 and b becomes 5. The straightforward way uses a temporary variable to hold one value while you overwrite it. But a very common C interview question asks you to do the same thing without any third (temporary) variable.

This is not because it is faster — it usually is not. It is because it forces you to think about how arithmetic and bitwise operators actually move data around. On this page you will learn four different ways to do it, see the exact output of each, and — just as important — learn where each method quietly breaks.

💡 The normal way (for comparison)

A clean, readable swap uses a temp variable: int t = a; a = b; b = t;. In real projects this is the right choice. The tricks below are for interviews and understanding.

Method 1: Addition and Subtraction

The idea is to store the combined value inside a, then peel each original value back out using subtraction.

C Language
#include <stdio.h>
int main() {
    int a = 5, b = 9;
    a = a + b;   // a = 14 (holds the total)
    b = a - b;   // b = 14 - 9 = 5 (original a)
    a = a - b;   // a = 14 - 5 = 9 (original b)
    printf("After swap: a = %d, b = %d\n", a, b);
    return 0;
}
Output:
After swap: a = 9, b = 5

Notice how each step uses the value produced by the previous step. The total (14) lives inside a until both originals have been recovered.

⚠️ The hidden danger

If a and b are both large, a + b can overflow the range of int (about 2.1 billion). When that happens the sum wraps around and the swap gives a wrong answer. This method is safe only for small values.

Method 2: Multiplication and Division

The same idea, but with multiply and divide instead of add and subtract.

C Language
#include <stdio.h>
int main() {
    int a = 5, b = 9;
    a = a * b;   // a = 45
    b = a / b;   // b = 45 / 9 = 5
    a = a / b;   // a = 45 / 5 = 9
    printf("After swap: a = %d, b = %d\n", a, b);
    return 0;
}
Output:
After swap: a = 9, b = 5
⚠️ Two problems

This method fails completely if either value is 0 (you would divide by zero). It also loses accuracy with numbers that do not divide evenly. Treat it as a curiosity, not a tool.

Method 3: XOR (bitwise) swap

The XOR operator (^) has a neat property: a value XOR-ed with itself becomes 0, and XOR is reversible. That lets us swap without any overflow risk.

C Language
#include <stdio.h>
int main() {
    int a = 5, b = 9;
    a = a ^ b;   // combine bits of a and b
    b = a ^ b;   // recovers original a into b
    a = a ^ b;   // recovers original b into a
    printf("After swap: a = %d, b = %d\n", a, b);
    return 0;
}
Output:
After swap: a = 9, b = 5

Because XOR works bit by bit and never carries, there is no overflow — this is its real advantage over the arithmetic method.

⚠️ The self-swap trap

If both variables are the same memory location (for example calling a swap function as swap(&x, &x)), XOR swap sets that variable to 0, because x ^ x is 0. Always check that the two addresses differ before XOR-swapping.

Method 4: The one-line trick

You can compress the addition method into a single line using the comma-free combined expression. It looks clever but is harder to read:

C Language
#include <stdio.h>
int main() {
    int a = 5, b = 9;
    a = a + b - (b = a);   // one-line swap
    printf("After swap: a = %d, b = %d\n", a, b);
    return 0;
}
Output:
After swap: a = 9, b = 5
💡 Good to know

One-liners like this rely on evaluation order and are easy to get wrong. Interviewers may show them, but you should not put them in real code — clarity beats cleverness.

Which method should you use?

MethodOverflow safe?Works with 0?Readable?
Temp variable (normal)YesYesBest
Addition / SubtractionNoYesOK
Multiplication / DivisionNoNoOK
XORYesYes*Tricky

*XOR is safe with 0 values, but not when both variables are the same location.

Common mistakes

  • Forgetting that addition can overflow for large numbers and silently give wrong results.
  • Using the multiply-divide method when a value might be 0.
  • Applying XOR swap on the same variable and zeroing it out by accident.
  • Writing an unreadable one-liner in production code just to look clever.
🏋️ Practice

Write a swap function void swap(int *x, int *y) using XOR, and add a check that skips the swap when x == y. Then test it by calling swap(&n, &n) to confirm it no longer zeroes the value.

Summary

  • Swapping without a third variable is an interview/learning exercise, not a performance trick.
  • Addition-subtraction is simple but can overflow.
  • Multiplication-division breaks on 0 and on non-even numbers.
  • XOR swap avoids overflow but fails when both operands share one address.
  • In real code, the plain temp-variable swap is clearest and just as fast.

Frequently Asked Questions

Is swapping without a third variable actually better in C?
Not usually. Modern compilers optimise a normal three-variable swap extremely well, and the temp-variable version is clearer to read. Swapping without a third variable is mostly an interview and learning exercise that tests your understanding of arithmetic and bitwise operators, not a real performance win.
Why can the addition-subtraction method fail?
Because a + b can exceed the range of an int and cause integer overflow. If both numbers are large, the sum wraps around and you get a wrong result. For safety with large values, prefer either a temp variable or the XOR method.
What happens if I XOR-swap a variable with itself?
If both operands are the same memory location (for example swap(&x, &x)), XOR swap sets that variable to 0, because x ^ x is 0. This is the classic hidden bug of XOR swap, so always guard against equal addresses.
Does the multiplication-division method work if one number is 0?
No. If either value is 0, the division step divides by zero and the program breaks. This is why the multiply-divide trick is considered unsafe and is rarely used in real code.
Which swap method do interviewers prefer to hear?
Most interviewers want you to first say the clean temp-variable swap is the correct real-world choice, then explain the XOR method and its self-swap edge case. Showing that you know the trade-offs matters more than reciting the trick.
← Back to C Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.