Swap two variables in one line in C/C+

In C programming, swapping two variables means exchanging the values stored in them. There are multiple ways to implement swapping using a single line statement. This article demonstrates various approaches to swap variable values efficiently.

Syntax

// General concept
variable1 = new_value_of_variable2;
variable2 = new_value_of_variable1;

Example Scenario

Let's consider the following input and expected output −

Input:
int a = 5;
int b = 10;

Output:
a = 10
b = 5

Method 1: Using Arithmetic Operations

This method uses arithmetic operations to swap variables without temporary storage. It works only with numeric types −

#include <stdio.h>

int main() {
    int a = 5, b = 10;
    printf("Before swap: a = %d, b = %d\n", a, b);
    
    a = a + b - (b = a);
    
    printf("After swap: a = %d, b = %d\n", a, b);
    return 0;
}
Before swap: a = 5, b = 10
After swap: a = 10, b = 5

Method 2: Using XOR Bitwise Operation

This approach uses bitwise XOR operation to swap variables. It works with integer types and doesn't require temporary storage −

#include <stdio.h>

int main() {
    int a = 5, b = 10;
    printf("Before swap: a = %d, b = %d\n", a, b);
    
    a = a ^ b ^ (b = a);
    
    printf("After swap: a = %d, b = %d\n", a, b);
    return 0;
}
Before swap: a = 5, b = 10
After swap: a = 10, b = 5

Method 3: Using Comma Operator

The comma operator can be used to perform multiple operations in a single statement −

#include <stdio.h>

int main() {
    int a = 5, b = 10, temp;
    printf("Before swap: a = %d, b = %d\n", a, b);
    
    temp = a, a = b, b = temp;
    
    printf("After swap: a = %d, b = %d\n", a, b);
    return 0;
}
Before swap: a = 5, b = 10
After swap: a = 10, b = 5

Comparison

Method Pros Cons Data Types
Arithmetic No temporary variable Risk of overflow Numeric only
XOR Fast bitwise operation Integer types only Integers
Comma Operator Clear and readable Uses temporary variable All types

Key Points

  • Arithmetic method may cause integer overflow for large values.
  • XOR method is efficient but limited to integer data types.
  • Comma operator method is most readable and works with all data types.

Conclusion

Single-line variable swapping in C can be achieved using arithmetic operations, XOR operations, or the comma operator. Choose the method based on your data types and readability requirements.

Updated on: 2026-03-15T09:58:46+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements