Introduction Assignment 5 — Swap Two Variables Without a Third Variable
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Swap the Values of Two Variables Without Using a Third Variable

📑 On this page:
  • Why swap without a third variable?
  • Two techniques: arithmetic and XOR
  • Complete C Programs
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • The classic swap algorithm using a temporary variable — and why it's usually the best choice
  • How to swap two integers using only addition and subtraction
  • How to swap two integers using the bitwise XOR operator
  • Why the XOR method works (XOR is its own inverse)
  • The overflow and zero-input caveats of both tricks
  • Why the temporary variable is still preferred in production code

Why swap without a third variable?

Swapping two variables is one of the oldest exercises in programming. The standard way uses a temporary:

int temp = a;
a = b;
b = temp;
                                

This is correct, clear, and works for any type. It's what you should use in real code, unless you have a specific reason not to. But "swap without a temporary" is a classic puzzle — and the puzzle is a good way to learn several deep ideas: how arithmetic can encode two values in one, how XOR works as a reversible operation, and how seemingly clever tricks have hidden pitfalls.

The motivation for the trick is memory savings — one fewer variable, one fewer 4 bytes. On modern hardware, this saving is negligible. A 4-byte temporary is nothing next to the megabytes of cache and gigabytes of RAM available. So the trick is rarely a real optimization. It's an intellectual exercise, a viva question, and a nice way to demonstrate some properties of arithmetic and bitwise operators.

Two techniques are common. The arithmetic method uses addition and subtraction: the sum of the two values encodes both, and subtracting the known original recovers the other. The XOR method uses the XOR operator, which has the property that x ^ x = 0 and x ^ 0 = x — so applying XOR twice with the same value undoes the operation, allowing you to recover the original values without any arithmetic overflow.

💡 In one line: you can swap two integers without a temporary by encoding both values in one variable (arithmetic or XOR), then decoding them back to their original forms in the opposite order. The trick is clever; the temp variable is still the better choice in real code.

Two boxes labelled a and b with values 5 and 10, shown before and after the swap — values exchanged without a temporary box in between.

Two techniques: arithmetic and XOR

Both techniques work by storing enough information in a to recover both original values, then using that information to reconstruct them. Here's how each one works.

1. The arithmetic method

Start with a = 5, b = 10.

  1. a = a + b; → a becomes 15 (the sum of both originals), b stays 10.
  2. b = a - b; → b becomes 15 − 10 = 5 (the original a), a stays 15.
  3. a = a - b; → a becomes 15 − 5 = 10 (the original b), b stays 5.

After three operations, a = 10, b = 5 — swapped. The sum 15 was the intermediate state that carried enough information to recover both originals. Once b was reconstructed to 5, a could be reconstructed to 10 using the same sum.

The catch: a + b can overflow if both operands are near INT_MAX. If a = 2,000,000,000 and b = 2,000,000,000, the sum 4,000,000,000 exceeds INT_MAX (2,147,483,647), and the result wraps around to a negative number. Subsequent subtractions then produce incorrect values. This is undefined behavior in the C standard — technically the compiler can do anything. In practice, on two's-complement systems, the wrap-around happens consistently, and the swap still works. But it's not portable, and it's a real bug source if you ever move to a platform with different overflow behavior.

2. The XOR method

Start with a = 5 (binary 0101), b = 10 (binary 1010).

  1. a = a ^ b; → a becomes 0101 ^ 1010 = 1111 = 15, b stays 10.
  2. b = a ^ b; → b becomes 1111 ^ 1010 = 0101 = 5 (the original a), a stays 15.
  3. a = a ^ b; → a becomes 1111 ^ 0101 = 1010 = 10 (the original b), b stays 5.

The key property: x ^ x = 0 and x ^ 0 = x. So when b XORs with the encoded value a, the original b bits cancel out (since they appear in both), leaving the original a bits. Then when a XORs with the now-restored b, the original a bits cancel out, leaving the original b. XOR is its own inverse — applying the same operation twice reverses it.

The XOR method avoids overflow entirely, because XOR is a bit-level operation with no carries. It works for any pair of integers within the type's range. The catch: if a and b are the same variable (same memory location), the swap fails — the first line sets a = a ^ a = 0, and the subsequent lines leave both at 0. This can happen with array indices or pointers. The arithmetic method has the same problem for the same reason (you can't swap a value with itself and expect the values to change — they're already the same).

Aspect Arithmetic XOR
Operations+ and −^ only
Overflow riskYes (if a + b overflows)No
Works for floatsYesNo (XOR is integer-only)
Works if a == &bNo (sets both to 0)No (sets both to 0)
ClarityModerateLow (obscure)
Best for productionNoNo — use a temp

Both methods are interesting — and worth knowing, for interviews and for understanding the underlying operators. But the temporary-variable swap is the right choice in real code, for three reasons: it works for any type (not just integers), it has no overflow caveats, and it's obvious to any reader.

🎯 Key idea: the no-temp swap is a puzzle, not an optimization. It's fun to learn, useful for interviews, and instructive for understanding XOR and arithmetic. But the temporary-variable version is clearer, safer, and works for more types. Use it in production; enjoy the trick in exercises.

Complete C Programs

Here is the complete program, showing both methods side by side:

Program: swap two integers with arithmetic, then with XOR

#include <stdio.h>

int main(void) {
    int a, b;

    printf("Enter two integers: ");
    scanf("%d %d", &a, &b);

    printf("\n--- Arithmetic method ---\n");
    printf("Before: a = %d, b = %d\n", a, b);

    /*
     * Step 1: a = a + b        (a holds the sum of both)
     * Step 2: b = a - b        (b recovers the original a)
     * Step 3: a = a - b        (a recovers the original b)
     */
    a = a + b;
    b = a - b;
    a = a - b;

    printf("After:  a = %d, b = %d\n", a, b);

    printf("\n--- XOR method ---\n");
    printf("Before: a = %d, b = %d\n", a, b);

    /*
     * Step 1: a = a ^ b        (a holds the XOR of both)
     * Step 2: b = a ^ b        (b recovers the original a)
     * Step 3: a = a ^ b        (a recovers the original b)
     *
     * XOR is its own inverse: x ^ x = 0, x ^ 0 = x.
     */
    a = a ^ b;
    b = a ^ b;
    a = a ^ b;

    printf("After:  a = %d, b = %d\n", a, b);

    return 0;
}
                                    

The program reads two integers, applies the arithmetic swap, prints the result, then applies the XOR swap (which swaps them back), and prints again. Since the two methods are inverses of themselves — each undoes its own swap — the final values are back to their originals.

And here's a step-by-step trace version, which prints the values of a and b after each line, so you can see the swap happen live:

Variant: trace each step

#include <stdio.h>

int main(void) {
    int a = 5, b = 10;

    printf("Start:        a = %2d, b = %2d\n", a, b);

    a = a + b;
    printf("a = a + b:    a = %2d, b = %2d\n", a, b);

    b = a - b;
    printf("b = a - b:    a = %2d, b = %2d\n", a, b);

    a = a - b;
    printf("a = a - b:    a = %2d, b = %2d\n", a, b);

    printf("\nNow swap back with XOR:\n\n");

    a = a ^ b;
    printf("a = a ^ b:    a = %2d, b = %2d\n", a, b);

    b = a ^ b;
    printf("b = a ^ b:    a = %2d, b = %2d\n", a, b);

    a = a ^ b;
    printf("a = a ^ b:    a = %2d, b = %2d\n", a, b);

    return 0;
}
                                    

This variant is more educational — you see each variable's value change at each step. Start with 5 and 10. After a = a + b, a holds 15 (the sum). After b = a - b, b becomes 15 − 10 = 5 (recovered original a). After a = a - b, a becomes 15 − 5 = 10 (recovered original b). Swapped! Then the XOR block swaps them back, with the same intermediate values but a different mechanism.

Program Output

Here is typical output from the first program:

Enter two integers: 5 10

--- Arithmetic method ---
Before: a = 5, b = 10
After:  a = 10, b = 5

--- XOR method ---
Before: a = 10, b = 5
After:  a = 5, b = 10
                                

The arithmetic method swapped 5 and 10 into 10 and 5. The XOR method then swapped them back into 5 and 10. Both methods did their job correctly — the arithmetic one for the swap, the XOR one for undoing it.

And here is the trace version:

Start:        a =  5, b = 10
a = a + b:    a = 15, b = 10
b = a - b:    a = 15, b =  5
a = a - b:    a = 10, b =  5

Now swap back with XOR:

a = a ^ b:    a = 15, b =  5
b = a ^ b:    a = 15, b = 10
a = a ^ b:    a =  5, b = 10
                                

The arithmetic trace is clear: 5, 10 → 15, 10 → 15, 5 → 10, 5. The XOR trace is the same pattern of intermediate values — 15 in a is the "combined" state, then it decomposes back. For this input, arithmetic and XOR produce the same intermediates because 5 + 10 = 5 ^ 10 = 15 (a coincidence of these particular bits). Try other inputs — like 3 and 7, or 12 and 5 — and the intermediates diverge, but the final swapped results always match.

With negative numbers:

Enter two integers: -5 10

--- Arithmetic method ---
Before: a = -5, b = 10
After:  a = 10, b = -5

--- XOR method ---
Before: a = 10, b = -5
After:  a = -5, b = 10
                                

Negative numbers work fine in both methods. The arithmetic one handles them because signed addition and subtraction are well-defined (unless overflow). The XOR one handles them because XOR operates on the bit patterns of the integers, and the two's-complement representation of negatives is well-suited to the trick.

With a potential overflow (both values near INT_MAX):

Enter two integers: 2000000000 2000000000

--- Arithmetic method ---
Before: a = 2000000000, b = 2000000000
After:  a = 2000000000, b = 2000000000

--- XOR method ---
Before: a = 2000000000, b = 2000000000
After:  a = 2000000000, b = 2000000000
                                

Both values being equal means the swap is a no-op — they both start and end at 2,000,000,000. The arithmetic method would overflow on the first line (a + b = 4,000,000,000, exceeding INT_MAX), but the subsequent subtractions happen to recover correctly on most two's-complement systems. The XOR method has no such concern — 2,000,000,000 ^ 2,000,000,000 = 0, but since both values are the same, the swap still leaves both equal. Try it with 2,000,000,000 and 1,000,000,000 to see the overflow case more clearly.

🔍 Try this: run the program with a = 2000000000 and b = 1000000000. The arithmetic method overflows, but on most systems the swap still works (though it's undefined behavior). The XOR method never overflows. This is the clearest demonstration of why the XOR method is "safer" for arbitrary integers — but also of why you should still just use a temporary variable and avoid the question entirely.

Step-by-Step Explanation

Let's walk through the arithmetic method and the XOR method in detail, then discuss the caveats.

1. The arithmetic method, step by step

Start with a = 5, b = 10.

  • Step 1: a = a + b; — a becomes 5 + 10 = 15. b stays 10. Now a encodes both original values: it's the sum. The originals are 5 and 10, and the sum is 15. Note that from a = 15 alone, you can't recover 5 and 10 — many pairs sum to 15. But you also have b = 10, so you can recover the 5 by subtracting: 15 − 10 = 5.
  • Step 2: b = a - b; — b becomes 15 − 10 = 5. a stays 15. Now b = 5, the original value of a. The "original a" has moved to b.
  • Step 3: a = a - b; — a becomes 15 − 5 = 10. b stays 5. Now a = 10, the original value of b. The "original b" has moved to a. Swap complete.

The elegance is in the intermediate state: a briefly holds the sum of both values. Then each original is recovered by subtracting the other. Since addition is commutative (a + b = b + a), the order doesn't matter — you can do a = a + b; b = a - b; a = a - b; or b = b + a; a = b - a; b = b - a; and both work.

2. The XOR method, step by step

Start with a = 5 (binary 0101), b = 10 (binary 1010).

  • Step 1: a = a ^ b; — bitwise XOR: 0101 ^ 1010 = 1111 = 15. a = 15, b = 10. Note that this time a doesn't hold the sum (arithmetic), it holds the XOR (bitwise). The value happens to be 15 here, same as the sum, but for different inputs the values differ.
  • Step 2: b = a ^ b; — 1111 ^ 1010 = 0101 = 5. a = 15, b = 5. The XOR with the original b bits "cancels out" the original b contribution in a, leaving the original a.
  • Step 3: a = a ^ b; — 1111 ^ 0101 = 1010 = 10. a = 10, b = 5. The XOR with the now-restored b bits cancels out the original a contribution in a, leaving the original b. Swap complete.

The key property is that XOR is its own inverse: (x ^ y) ^ y = x. So when you XOR a value with the same thing twice, you get the original. In step 2, a ^ b where a is the XOR of the originals and b is the original b — that leaves the original a. In step 3, a ^ b where a is again the XOR of the originals and b is now the recovered original a — that leaves the original b.

3. Why XOR works: the algebraic property

XOR (exclusive OR) satisfies three useful properties:

  • Commutative: x ^ y = y ^ x
  • Associative: (x ^ y) ^ z = x ^ (y ^ z)
  • Self-inverse: x ^ x = 0, and x ^ 0 = x

Together, these imply that (x ^ y) ^ y = x ^ (y ^ y) = x ^ 0 = x. Apply that to the swap:

  • After step 1, a = x ^ y, b = y.
  • Step 2: b = a ^ b = (x ^ y) ^ y = x. Now b = x.
  • Step 3: a = a ^ b = (x ^ y) ^ x = y. Now a = y.

The swap works because x and y "cancel out" in the right order. It's a bit of algebraic sleight-of-hand, made possible by XOR's self-inverse property.

4. The overflow problem with arithmetic

If a and b are both positive and their sum exceeds INT_MAX (about 2.1 billion on typical systems), the addition a + b overflows. In C, signed integer overflow is undefined behavior — the compiler can technically do anything, though in practice on two's-complement systems it wraps around to a negative number. The subsequent subtractions may still produce the correct swap (because the wrap-around and the two's-complement arithmetic are consistent), but it's not portable, and a compiler could legitimately produce incorrect code.

The XOR method has no overflow problem, because XOR is a bit-level operation with no carries. Any pair of integers can be safely XOR-swapped without overflow. This is one reason the XOR method is sometimes preferred over the arithmetic method — though for production code, using a temporary variable is the safest choice of all.

5. The aliasing problem

Both methods fail if a and b are the same variable, i.e., they alias the same memory location. For example:

int x = 5;
int *p = &x;
int *q = &x;  /* p and q point to the same location */
                                

If you try to swap through p and q with any of these methods, you'd be modifying the same variable through two names — and the intermediate operations corrupt the value. For example, in the arithmetic method: *p = *p + *q; writes 10 to x. Then *q = *p - *q; reads 10 from x (through both p and q), computes 10 − 10 = 0, writes 0 to x. Then *p = *p - *q; computes 0 − 0 = 0, writes 0. Result: x = 0, not 5. The swap fails.

The temporary-variable swap doesn't have this problem: int temp = *p; *p = *q; *q = temp; works correctly even when p == q, because the intermediate value is stored in a separate variable, not in the aliased location.

6. Why the temporary is still the right choice

The no-temp tricks are clever, and they demonstrate interesting properties of arithmetic and bitwise operators. But in real code, the temporary-variable swap is the right choice:

  • Clarity: temp = a; a = b; b = temp; is obvious to any reader. The XOR version is obscure — a reader has to think about whether it's correct.
  • Correctness: the temporary works for any type, including floating-point, structures, pointers, and arrays of any size. XOR only works for integers.
  • No overflow: the temporary doesn't do arithmetic on the values, so overflow is never an issue.
  • Aliasing: the temporary works even when the two values are in the same location. The tricks don't.

The memory savings of one temporary variable (typically 4 bytes for an int, 8 for a double, or the size of the type) are negligible. On a machine with gigabytes of RAM, saving 8 bytes is meaningless. The cost of clarity and correctness is much higher than the benefit of memory savings.

🎯 Key idea: the temporary-variable swap is the right choice in real code — it's clear, correct for any type, and has no hidden caveats. The no-temp tricks are fascinating and worth learning, but they're puzzles, not optimizations. Use the temp; enjoy the tricks.

Frequently Asked Questions

1. Which is faster — the temp variable or the XOR trick?

On modern compilers, they're essentially the same. The compiler recognizes both patterns and emits efficient code — often the same code for both. The "memory savings" of the no-temp trick are eliminated by the compiler's register allocation, which puts both variables and the intermediate values in CPU registers. So there's no performance advantage to either method — pick the one that's clearer to read, which is the temporary variable.

2. Why doesn't the XOR trick work for floats?

Because XOR is a bitwise operator, which only operates on integer types. Floats are stored as IEEE 754 floating-point values (sign bit, exponent, mantissa), and bitwise operations on them don't have the same algebraic properties as on integers. There is no equivalent "reversible" bitwise operation for floats that would allow the swap trick. So for floats, you must use a temporary (or arithmetic — which works for floats, since + and − are defined for them).

3. What happens if a and b are the same variable?

Both tricks fail. For the XOR version: a = a ^ a = 0; then b = a ^ b = 0 ^ 0 = 0; then a = a ^ b = 0 ^ 0 = 0. So both end up 0. For the arithmetic version: a = a + a = 2a; then b = a - b = 2a - a = a; then a = a - b = a - a = 0. Both end up 0. The temporary-variable swap works fine in this case (because temp is separate), so it's the safe choice when aliasing is possible.

4. What's the overflow problem with the arithmetic swap?

If a + b exceeds INT_MAX (or, for subtraction, drops below INT_MIN), the arithmetic overflows. In C, signed integer overflow is undefined behavior — the standard doesn't specify what happens. In practice, on two's-complement systems, the result wraps around to a negative number, and the subsequent subtractions often still produce the correct swap. But this is not portable, and a compiler is technically allowed to produce incorrect code. The XOR method has no such issue (XOR never overflows), and the temporary variable has no such issue either.

5. When would you actually use the no-temp swap?

Almost never, in production code. The trick is useful in two contexts: (a) as an interview or viva question to demonstrate understanding of operators, and (b) in code golf or obfuscated code contests, where terseness is the goal. It's also useful in embedded systems where every byte of RAM is precious (very rare nowadays, given modern microcontrollers typically have at least a few KB). But for general-purpose software, the temporary-variable swap is safer and clearer. Use the temp.

6. Why does the arithmetic method work even though a + b "loses" information?

It doesn't really lose information — the sum a + b, together with one of the original values, is enough to recover the other. The full state after step 1 is (a + b, b). From this, you can recover b (= b, unchanged) and a (= (a + b) − b). Step 2 uses that: b becomes (a + b) − b = a. Then step 3 uses the new (a + b, a) to recover b = (a + b) − a. Each step preserves enough information to recover the originals; no information is lost, it's just rearranged. The same applies to XOR, with XOR's inverse property replacing subtraction.

💡 Tip: once this works, try the assignment with pointers instead of integers. int *p = &a; int *q = &b; — the swap is *p = *p + *q; *q = *p - *q; *p = *p - *q;. Same trick, but now applied through pointers. Then try it with p == q (both pointing to the same variable) — see the failure mode first-hand. That's why the temporary variable exists.

📖 Related Tutorials

  • Previous: Declaration and Initialization of Variables of Different Data Types
  • Next: Area of a Rectangle by Accepting Length and Width
  • Arithmetic Operators in C
  • Bitwise Operators in C
  • Operators and Expressions
  • Built-in Data Types in C
  • All 13 Introduction to C Assignments

Previous Topic: -->> 4. Declaration and Initialization of Variables of Different Data Types   ||   Next Topic: -->> 6. Area of a Rectangle by Accepting Length and Width


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.