Swap Two Numbers Without a Third Variable in C
Exchange the values of two integer variables in C without using a temporary variable.
- Time
O(1) - Space
O(1) - Hints3
- Read3 min
To swap a and b without a third variable in C, use three steps: a = a + b; b = a - b; a = a - b;. After them, a holds the old b and b holds the old a. The XOR version a ^= b; b ^= a; a ^= b; also works and cannot overflow. In real code a temporary variable is clearer, but this question is common in labs and vivas because it tests how well you understand operators.
Problem statement
Write a C program to swap two numbers without a third variable. Given
a = 10 and b = 20, after the swap a should be 20 and b should be 10.
Do not declare a temp variable. Use arithmetic or bitwise operators.
Two integers a and b.
The values of a and b before and after the swap.
Examples
a = 10, b = 20a = 20, b = 10a becomes 30, then b becomes 30 - 20 = 10, then a becomes 30 - 10 = 20.
a = 5, b = 9 (XOR method)a = 9, b = 5XOR-ing twice with the same value gives back the original.
Constraints
- For the + and - method, a + b must fit in an int
- For the * and / method, neither value can be 0 and a * b must fit in an int
Think before you code
Reveal the questions to ask yourself first
- If
aholds the sum of both numbers, how can you get the oldaback? - Which variable should you change first?
- What could go wrong if
a + bis very large?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
Method 1: addition and subtraction
a = a + b; /* a holds the sum */
b = a - b; /* sum - old b = old a */
a = a - b; /* sum - old a = old b */
Method 2: XOR
x ^ x = 0 and x ^ 0 = x. So (a ^ b) ^ b gives back a.
a = a ^ b;
b = a ^ b; /* (a ^ b) ^ b = old a */
a = a ^ b; /* (a ^ b) ^ old a = old b */
Method 3: multiplication and division
a = a * b; b = a / b; a = a / b; works only when neither number is 0 and the
product fits in an int.
| Method | Works with 0? | Overflow risk | Works for float? |
|---|---|---|---|
| + and - | Yes | Yes, if a + b is too big | Yes, with rounding error |
| XOR | Yes | No | No, XOR needs integers |
| * and / | No | Yes, and larger | Yes, with rounding error |
| temp variable | Yes | No | Yes |
Dry run
Walk through the example step by step
Addition method, a = 10, b = 20:
step | a | b
-------------+----+----
start | 10 | 20
a = a + b | 30 | 20
b = a - b | 30 | 10
a = a - b | 20 | 10
XOR method, a = 5 (0101), b = 9 (1001):
step | a | b
-------------+------------+-----------
start | 0101 (5) | 1001 (9)
a = a ^ b | 1100 (12) | 1001 (9)
b = a ^ b | 1100 (12) | 0101 (5)
a = a ^ b | 1001 (9) | 0101 (5)
Solution
Reveal the full C solution
#include <stdio.h>
int main(void) {
int a = 10, b = 20;
printf("Before swap: a = %d, b = %d\n", a, b);
a = a + b; /* a = 30 */
b = a - b; /* b = 30 - 20 = 10 */
a = a - b; /* a = 30 - 10 = 20 */
printf("After swap: a = %d, b = %d\n", a, b);
return 0;
}Output:
Before swap: a = 10, b = 20
After swap: a = 20, b = 10
Swap two numbers using XOR in C, and the * / method
#include <stdio.h>
int main(void) {
int a = 5, b = 9;
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("a = %d, b = %d\n", a, b);
int x = 4, y = 7;
x = x * y; /* 28 */
y = x / y; /* 4 */
x = x / y; /* 7 */
printf("x = %d, y = %d\n", x, y);
return 0;
}
a = 9, b = 5
x = 7, y = 4
Swap with user input and a function
To swap the caller's variables, a function needs their addresses. Passing plain ints would only swap copies.
#include <stdio.h>
void swap(int *p, int *q) {
if (p == q) {
return;
}
*p = *p + *q;
*q = *p - *q;
*p = *p - *q;
}
int main(void) {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
swap(&a, &b);
printf("After swap: a = %d, b = %d\n", a, b);
return 0;
}
Enter two numbers: 15 -4
After swap: a = -4, b = 15
The p == q check matters. If both pointers point to the same variable, the first
line doubles it and the second line sets it to 0, so the value is lost. The XOR
version has the same problem.
Why is this asked in vivas?
It checks three things in one short question: that you understand how assignment
changes a variable step by step, that you know operators beyond +, and that you can
spot limits such as overflow and the zero case. Be ready to say that in real
programs a temp variable is clearer and just as fast with modern compilers.
The Java version is on swap two numbers without a third variable. More lab programs are in C programs for beginners, and pointer basics are in what is a pointer in C.
O(1)O(1)Review before the interview
Common mistakes
- Writing b = a - b before a = a + b. The order of the three lines is fixed.
- Using the * and / method when one value is 0, which divides by zero.
- Writing a swap function that takes int a, int b. It swaps copies, and main sees no change.
- Writing it in one line as a = a + b - (b = a). This mixes a read and a write of b without a sequence point, which is undefined behaviour in C.
Edge cases to test
- Equal values: a = b = 7 still works with + and - and with XOR.
- Negative numbers work with + and - and with XOR.
- Large values: 2000000000 + 2000000000 overflows a 32-bit int, which is undefined behaviour for signed ints. XOR has no such risk.
- Same variable through pointers: swap(&a, &a) sets a to 0 without the p == q check.
Interview follow-ups
- Why does XOR swapping fail when both pointers point to the same variable?
- How would you swap two numbers in one line in Python?
- Can you swap two strings without a third variable?
Keep practising
Swap Two Numbers Without Using a Third Variable
Hints · Dry run · SolutionSolve Similar problemSwap the First and Last Digits of a Number
Hints · Dry run · SolutionSolve Similar problemCheck Whether a Number Is Even or Odd Without the Modulus Operator
Hints · Dry run · SolutionSolve Related learningWhat Is A Pointer In C
TutorialLearn Related learningLearn C Programming Step By Step
TutorialLearn Related learningC Programming Interview Questions
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartBuilding your programming basics?
CodeBegun’s programs build problem-solving with mentor review and mock interviews, online or in Madhapur, Hyderabad.
