Swapping two variable value without using third variable in C/C++

In C programming, swapping two variables without using a third variable can be accomplished using arithmetic operations. This technique saves memory and demonstrates clever use of mathematical operations.

Syntax

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

Method 1: Using Addition and Subtraction

This approach uses arithmetic operations to swap values without requiring additional memory −

#include <stdio.h>

int main() {
    int a = 10, b = 20;
    
    printf("Before swapping: a = %d, b = %d\n", a, b);
    
    a = a + b;  // a becomes 30 (10 + 20)
    b = a - b;  // b becomes 10 (30 - 20)
    a = a - b;  // a becomes 20 (30 - 10)
    
    printf("After swapping: a = %d, b = %d\n", a, b);
    return 0;
}
Before swapping: a = 10, b = 20
After swapping: a = 20, b = 10

Method 2: Using XOR Operation

The XOR bitwise operation provides another efficient way to swap variables −

#include <stdio.h>

int main() {
    int a = 15, b = 25;
    
    printf("Before swapping: a = %d, b = %d\n", a, b);
    
    a = a ^ b;  // XOR of a and b
    b = a ^ b;  // XOR again to get original a
    a = a ^ b;  // XOR to get original b
    
    printf("After swapping: a = %d, b = %d\n", a, b);
    return 0;
}
Before swapping: a = 15, b = 25
After swapping: a = 25, b = 15

Method 3: Using Single Line Expression

All operations can be combined into a single line using the comma operator −

#include <stdio.h>

int main() {
    int a = 50, b = 75;
    
    printf("Before swapping: a = %d, b = %d\n", a, b);
    
    a = a + b - (b = a);  // Single line swap
    
    printf("After swapping: a = %d, b = %d\n", a, b);
    return 0;
}
Before swapping: a = 50, b = 75
After swapping: a = 75, b = 50

Comparison

Method Pros Cons Risk
Addition/Subtraction Simple logic Possible overflow Integer overflow with large values
XOR Operation No overflow risk Works only with integers None
Single Line Compact code Harder to read Undefined behavior in some cases

Key Points

  • These methods work only with numeric data types.
  • XOR method is safest as it avoids overflow issues.
  • For production code, using a temporary variable is often clearer and safer.

Conclusion

Swapping without a third variable demonstrates efficient memory usage in C. While these techniques are clever, they should be used carefully considering readability and potential overflow issues.

Updated on: 2026-03-15T10:00:50+05:30

599 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements