Operators Assignment 12 — Swap Two Numbers Without a Temporary Variable
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Swap Two Numbers Without a Temporary Variable

📑 On this page:
  • Two ways to swap without a temp
  • Method 1 — addition/subtraction
  • Method 2 — bitwise XOR
  • Complete C Programs
  • Program Output
  • Step-by-Step Explanation
  • Warnings and caveats
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to swap two numbers using only + and −
  • How to swap two numbers using only XOR (^)
  • Why the XOR method is "safer" than addition/subtraction in some cases
  • The overflow and aliasing caveats of both methods
  • Why the temp-variable version is the standard idiom in production code

Two ways to swap without a temp

The standard way to swap two variables is with a temporary:

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

That's three lines, one extra variable, and it always works. But there are two classic alternatives that avoid the temporary entirely — using arithmetic or using XOR. Both are worth knowing: they're common in puzzle contexts, interview questions, and legacy code, and they illustrate useful properties of the operators involved.

The two methods:

  • Addition/subtraction: a = a + b; b = a − b; a = a − b;
  • Bitwise XOR: a = a ^ b; b = a ^ b; a = a ^ b;

Both rely on the trick of storing enough information in a and b combined to reconstruct both original values, then extracting them one at a time.

💡 In one line: both methods work because (a + b) − b = a and (a ^ b) ^ b = a — each method undoes itself, letting you "recover" the original a from the combined value.
Swap two numbers without a temp variable in C — side-by-side comparison of the addition/subtraction and XOR methods.

Method 1 — addition/subtraction

The idea: temporarily store the sum in a, then use the sum to reconstruct b's original value (as sum − a_orig), then use the new b to reconstruct a's original value.

Trace with a = 5, b = 7:

Step Operation a b Note
0—57Initial
1a = a + b127a = 5 + 7 = 12
2b = a − b125b = 12 − 7 = 5 (= original a)
3a = a − b75a = 12 − 5 = 7 (= original b)

After three steps, a = 7, b = 5 — the values are swapped. No temporary variable was needed. The arithmetic works for any two integers (with the overflow caveat below).

Method 2 — bitwise XOR

The idea: XOR has the property x ^ x = 0 and x ^ 0 = x. So XORing with the same value twice "cancels out" — exactly what we need to reconstruct an original value after combining two variables.

Trace with a = 5, b = 7 (binary 0101 and 0111):

Step Operation a b Note
0—5 (0101)7 (0111)Initial
1a = a ^ b2 (0010)7 (0111)a = 0101 ^ 0111 = 0010
2b = a ^ b2 (0010)5 (0101)b = 0010 ^ 0111 = 0101 (= original a)
3a = a ^ b7 (0111)5 (0101)a = 0010 ^ 0101 = 0111 (= original b)

After three steps, a = 7, b = 5 — swapped. The XOR method works for any two integers, signed or unsigned, because XOR operates on the bit patterns directly.

Complete C Programs

Program 1 — using addition/subtraction:

Program 1: Swap using + and −

#include <stdio.h>

int main(void) {
    int a, b;

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

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

    a = a + b;
    b = a - b;
    a = a - b;

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

    return 0;
}
                                

Program 2 — using bitwise XOR:

Program 2: Swap using XOR

#include <stdio.h>

int main(void) {
    int a, b;

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

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

    a = a ^ b;
    b = a ^ b;
    a = a ^ b;

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

    return 0;
}
                                

Both programs produce identical output — the choice between methods is stylistic. The XOR version is often called the "classic XOR swap."

Program Output

Running either program with 5 7:

Enter two integers: 5 7
Before swap: a = 5, b = 7
After swap:  a = 7, b = 5
                            

Values are swapped. Correct.

With negative numbers:

Enter two integers: -3 8
Before swap: a = -3, b = 8
After swap:  a = 8, b = -3
                            

Both methods handle negatives correctly. The XOR method handles any signed value uniformly (bit pattern manipulation); the addition method also works, as long as intermediate sums don't overflow.

With equal values:

Enter two integers: 5 5
Before swap: a = 5, b = 5
After swap:  a = 5, b = 5
                            

Identical values produce identical "swapped" values — which makes sense, since swapping equal values has no visible effect.

Step-by-Step Explanation

1. Reading inputs: scanf("%d %d", &a, &b) reads two integers into a and b. The & is the address-of operator.

2. Why addition/subtraction works: In step 1, a becomes a + b. In step 2, b becomes (a + b) − b = a — the original a. In step 3, a becomes (a + b) − a = b (using the new b, which is the original a). Both original values are recovered.

3. Why XOR works: In step 1, a becomes a ^ b. In step 2, b becomes (a ^ b) ^ b = a ^ (b ^ b) = a ^ 0 = a — the original a. In step 3, a becomes (a ^ b) ^ a = b ^ (a ^ a) = b ^ 0 = b — the original b. Both original values are recovered.

4. Why XOR is "safer": The XOR method doesn't involve any arithmetic overflow. XOR always produces a value that fits in the type, so no wraparound happens mid-swap. The addition/subtraction method, on the other hand, can overflow at step 1 if a + b exceeds the type's range. For example, if a = 2,000,000,000 and b = 2,000,000,000 (both positive, both fitting in int), their sum overflows and gives a negative number, and the subsequent steps produce wrong results.

5. The aliasing problem: Both methods fail when a and b refer to the same variable (i.e., swap(&x, &x) in a pointer-based version). If a and b are the same memory location:

  • XOR: a = a ^ a = 0, then b = 0 ^ 0 = 0 (but b is the same as a), then a = 0 ^ 0 = 0. Both become 0.
  • Addition: a = a + a = 2a, then b = 2a − a = a, then a = 2a − a = a. Actually this works — it produces a unchanged.

Wait — the XOR aliasing case is the classic bug: if both operands point to the same location, XOR zeroes both. But in our single-variable-pair program, a and b are distinct variables, so this isn't an issue. It becomes an issue in swap(int *p, int *q) when p == q.

6. Compiler optimizations: Modern compilers recognize both swap idioms and may optimize them back to the temp-variable version (or even a single instruction on some architectures). The "no temp variable" claim is more of a puzzle-piece than a performance optimization — using temp is almost always at least as fast and clearer.

7. When to use which: For general code, use the temp-variable swap — it's clear, correct, and safe. Use the XOR swap if you're specifically solving a puzzle that forbids a temp variable, or if you're working in a context where temp registers are at a premium (some assembly-language contexts, but almost never C). Use addition/subtraction only if you're handling values that you know can't overflow. In production code, "swap without temp" is nearly always a red flag — it's clever but fragile.

⚠️ Caution: both "swap without temp" methods have subtle pitfalls (overflow for +/−, aliasing for XOR). They're excellent learning exercises, but for real code, use temp. The three-line temp swap is what every experienced programmer writes, and what every compiler optimizes best.

Warnings and caveats

Before reaching for these tricks, know their limitations:

  • Overflow. The addition method overflows if a + b exceeds the type's range. For int, that's about ±2.1 billion. Two large positive values, two large negative values, or one of each at extreme magnitudes can all overflow.
  • Aliasing. Both methods fail (in different ways) if a and b are the same variable. XOR zeroes the value; addition leaves it unchanged (by accident, not design). In pointer-based swap, this happens when the same pointer is passed twice.
  • Readability. Nobody reading your code expects a XOR swap. Even if it works, it takes longer to understand than the temp-variable version. In a team codebase, clarity usually wins over cleverness.
  • Performance. Modern compilers recognize the temp-variable swap and optimize it to the best machine code — often the same as (or better than) the "clever" versions. There's no performance advantage to avoiding temp.
  • Undefined behavior. Signed integer overflow is undefined behavior in C. If the addition method overflows, the compiler is not required to produce "wraparound" — it may produce garbage, crash, or optimize away subsequent code. This is a real concern in production code.

The XOR method avoids overflow (XOR is always defined for all bit patterns) but has the aliasing issue. Neither is strictly "safe" in all cases. Use them for learning; use temp for production.

Frequently Asked Questions

1. Which method is better — addition/subtraction or XOR?

XOR is generally considered better for the "swap without temp" puzzle because it doesn't overflow and works uniformly on all bit patterns. Addition/subtraction can overflow with large values, producing wrong results. But for real code, the temp-variable version is best: it's clear, safe, and optimized by the compiler. Choose XOR over +/− if you must avoid temp; choose temp over XOR for production code.

2. What happens with negative numbers?

Both methods handle negatives. The XOR method is straightforward — it operates on the bit pattern, and two's complement preserves the values. The addition method also works: for a = −3, b = 8, step 1 gives a = 5, step 2 gives b = −3, step 3 gives a = 8. Correct. The only concern is overflow, which can affect both positive and negative values (e.g., INT_MAX + 1 overflows, INT_MIN − 1 underflows).

3. Can I swap floating-point numbers this way?

Addition/subtraction works for floats and doubles (with precision caveats — floating-point addition isn't always exact, so the round-trip (a + b) − b may not equal a exactly). XOR does NOT work for floats — the ^ operator is defined only for integers. For floats, use addition/subtraction if you must avoid a temp, but be aware of precision loss; better to just use a temp.

4. Why do people say "XOR swap is dangerous"?

Two reasons. First, if both operands are the same variable (aliasing), XOR zeroes the value. For example, swap(&x, &x) with int *a = &x; int *b = &x; would zero x. Second, the code is non-obvious — future readers might not immediately understand what it does, and might "fix" it wrongly. In team codebases, unfamiliar idioms are a maintenance hazard. The temp-variable version has neither issue.

5. Does the compiler optimize these tricks?

Yes — modern compilers (GCC, Clang, MSVC) recognize both "swap without temp" patterns and can optimize them. In some cases, the compiler generates the same code as the temp-variable version. In extreme cases, it may even inline a single XCHG instruction (on x86). This is another reason the "cleverness" doesn't pay off — the compiler already knows how to swap efficiently, and it doesn't need your help.

💡 Tip: after understanding both methods, try implementing a swap(int *p, int *q) function using pointers, and test it with swap(&x, &x) to see the aliasing bug in action. Then rewrite with a temp variable and observe that swap(&x, &x) works correctly (x is unchanged). This shows why the temp-variable version is the robust choice, and it's a good exercise in pointer reasoning.

📖 Related Tutorials

  • Previous: Check Even/Odd Using Bitwise AND
  • Next: Find Minimum of Two Numbers Without 'if'
  • Bitwise XOR on Two Numbers Using '^'
  • Toggle a Particular Bit Using XOR
  • Bitwise Operators in C — Full Tutorial
  • All 15 Operator Assignments in C
  • Operators FAQ

Previous Topic: -->> 11. Check if a Number is Even or Odd Using Bitwise AND   ||   Next Topic: -->> 13. Find the Minimum of Two Numbers Without Using 'if'


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.