- num1
- 5
- num2
- 10
Swap Two Numbers in C++
What you’ll learn
- What swapping means in everyday terms (two values trade places).
- The classic three-step pattern with a
tempvariable—and why you need it. - A version with pointers so a function can change variables in
main, plus a version that stays entirely inmain. - An XOR pattern that swaps without any
tempvariable (integers only, with important caveats). - A live preview, short notes on arithmetic swaps, and interview-style pitfalls.
Overview
You have two labeled boxes, num1 and num2. Swapping means: whatever was inside the first box moves to the second, and whatever was in the second moves to the first. A third spare box, temp, holds one value for a moment so nothing gets erased too early.
Three code examples
Example 1: pointers and temp. Example 2: same idea inside main. Example 3: XOR swap with no extra variable.
Live preview
Type two integers and press Swap to see “before” and “after” lines that match the C idea.
Extras you may hear in class
After Example 3, the notes recap why add/subtract swaps can overflow and why temp stays the default in real code.
Prerequisites
You should know what a variable is and how to print integers with std::cout.
#include <iostream>,int main(), and assignmenta = b;.- For Example 1: the idea that
&num1means “address ofnum1” (a pointer). If that is new, read Example 2 first.
What does swapping do?
After a correct swap, the first variable shows the value the second used to have, and the second shows what the first used to have. Order matters in sorting; swapping is the smallest “exchange” step.
Picture two full cups. You cannot pour both into each other at once without spilling. So you use a third empty cup (temp) to hold one drink while you move the other.
Why pointers inside a function?
In C, when you pass int x into a function, the function receives a copy. Swapping copies inside the helper does not change num1 and num2 back in main. Passing int *a and int *b means “here are the addresses of the real variables”—so *a and *b read and write the originals.
swapNumbers(&num1, &num2) says “swap whatever lives at these two addresses.” Inside the function, *a is another name for num1’s storage.
Trace on paper
- Why
- Save the old
num1before overwriting it.
- num1
- 10
- num2
- 5
Live preview
Uses the same three-step pattern as the C samples. Values stay inside JavaScript safe integers.
Algorithm
Goal: exchange the values in two integer variables using a temporary third integer.
Copy first into temp
temp = a; (or temp = *a; when using pointers).
Move second into first
a = b; (or *a = *b;).
Move saved value into second
b = temp; (or *b = temp;).
📜 Pseudocode
procedure swap(a, b): // a and b name two storage slots
temp ← a
a ← b
b ← temp Function with pointers (classic interview style)
swapNumbers takes addresses so the swap survives after the function returns. &num1 passes the address of num1.
#include <iostream>
void swapNumbers(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int num1 = 5;
int num2 = 10;
std::cout << "Before swapping: num1 = " << num1 << ", num2 = " << num2 << "\\n";
swapNumbers(&num1, &num2);
std::cout << "After swapping: num1 = " << num1 << ", num2 = " << num2 << "\\n";
return 0;
} Explanation
int temp = *a;Save the first value. The star (*) reads whatever lives at address a.
*a = *b; *b = temp;Finish the exchange. First overwrites the first slot with the second value, then restores the saved value into the second slot.
All in main (no pointers needed)
Same three moves, but the variables are ordinary ints in main. This is often the easiest version on day one of C.
#include <iostream>
int main() {
int num1 = 5;
int num2 = 10;
int temp;
std::cout << "Before swapping: num1 = " << num1 << ", num2 = " << num2 << "\\n";
temp = num1;
num1 = num2;
num2 = temp;
std::cout << "After swapping: num1 = " << num1 << ", num2 = " << num2 << "\\n";
return 0;
} Explanation
When everything lives in one function, plain assignments already touch the real variables—no & or * required.
Without any temp variable (XOR, integers only)
Three XOR assignments shuffle bits so the values trade places without a third integer variable. This only works cleanly for integer types where XOR is defined. The early if (a == b) return; matters when both pointers refer to the same variable—otherwise the three lines would zero it out.
#include <iostream>
void swapXor(int *a, int *b) {
if (a == b) {
return;
}
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
int main() {
int num1 = 5;
int num2 = 10;
std::cout << "Before swapping: num1 = " << num1 << ", num2 = " << num2 << "\\n";
swapXor(&num1, &num2);
std::cout << "After swapping: num1 = " << num1 << ", num2 = " << num2 << "\\n";
return 0;
} Explanation
^= is XOR-then-assign. Each step mixes the two values; after three applications the bits end up exchanged. You do not need to memorize the proof for interviews—just know it is a clever integer trick, not a replacement for temp in most team code.
if (a == b) return;Same address guard. If swapXor(&x, &x) were allowed to run, all three XORs would hit the same memory and could clear x to zero.
*a ^= *b; *b ^= *a; *a ^= *b;No spare variable. Only works for types where bitwise XOR behaves as expected (typically integers). Floats and pointers are different stories—stick to temp there.
Other tricks (read after you know temp)
XOR swap. Full program in Example 3. Prefer temp for readability unless a style guide or embedded constraint says otherwise.
Add/subtract swap. Ideas such as a = a + b; b = a - b; a = a - b; can overflow fixed-width integers. Prefer temp for correctness and clarity.
Interview: show the pointer version first; mention that copies inside a naive void swap(int x, int y) would not work.
❓ FAQ
🔄 Input / output examples
Each sample prints two lines (before and after). Replace the literals or use std::cin >> num1 >> num2; for interactive input.
| num1, num2 (before) | After swap |
|---|---|
| 5, 10 | 10, 5 |
| 0, 3 | 3, 0 |
| -4, 20 | 20, -4 |
| 7, 7 | 7, 7 |
Edge cases
Most mistakes come from forgetting why pointers exist, or from “clever” swaps that overflow.
void swap(int x, int y)
Swaps only the local copies; main never changes. Use pointers or do the swap directly in main.
Never start with a = b alone
You lose the original a and cannot recover it for b without a saved copy.
Arithmetic swaps
Adding two large signed integers can overflow undefined behavior in C++. Stick to temp unless you control the range.
Same pointer twice
Calling the XOR version with the same address for both parameters needs the a == b guard in Example 3; otherwise the value can be wiped to 0.
⏱️ Time and space complexity
| Version | Time | Extra space |
|---|---|---|
| Temp swap (Examples 1 & 2) | O(1) | O(1) (one integer) |
| XOR swap (Example 3) | O(1) | O(1) (no extra variable) |
| Add/subtract trick | O(1) | O(1); watch overflow |
Summary
- Pattern:
temp = a; a = b; b = temp;(or pointer versions of the same story). - Functions: take
int *and use*aso you edit the caller’s variables. - Extras: Example 3 shows XOR without
temp; add/subtract exists too—tempstays the readable default.
Swapping two values is a tiny step inside bigger ideas such as sorting (for example bubble sort compares and swaps neighbors). The three-line pattern with a temp variable is the clearest way to explain what “exchange” means in C++ programs.
8 people found this page helpful
