Swap Two Numbers in C

Beginner
⏱️ 10 min read
📚 Updated: May 2026
🎯 3 Code Examples
Variables & pointers

What you’ll learn

  • What swapping means in everyday terms (two values trade places).
  • The classic three-step pattern with a temp variable—and why you need it.
  • A version with pointers so a function can change variables in main, plus a version that stays entirely in main.
  • An XOR pattern that swaps without any temp variable (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 printf.

  • #include <stdio.h>, int main(void), and assignment a = b;.
  • For Example 1: the idea that &num1 means “address of num1” (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.

Memory aid

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

Start Before
num1
5
num2
10
temp Holds 5
Why
Save the old num1 before overwriting it.
Done After
num1
10
num2
5

Live preview

Uses the same three-step pattern as the C samples. Values stay inside JavaScript safe integers.

Enter integers (try negatives too). Press Swap or Enter in either field.

Live result
Press “Swap” to see before and after values.

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

Pseudocode
procedure swap(a, b):  // a and b name two storage slots
    temp ← a
    a ← b
    b ← temp
1

Function with pointers (classic interview style)

swapNumbers takes addresses so the swap survives after the function returns. &num1 passes the address of num1.

c
#include <stdio.h>

void swapNumbers(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main(void) {
    int num1 = 5;
    int num2 = 10;

    printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);
    swapNumbers(&num1, &num2);
    printf("After swapping: num1 = %d, num2 = %d\n", num1, num2);

    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.

2

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.

c
#include <stdio.h>

int main(void) {
    int num1 = 5;
    int num2 = 10;
    int temp;

    printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);

    temp = num1;
    num1 = num2;
    num2 = temp;

    printf("After swapping: num1 = %d, num2 = %d\n", num1, num2);

    return 0;
}

Explanation

When everything lives in one function, plain assignments already touch the real variables—no & or * required.

3

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.

c
#include <stdio.h>

void swapXor(int *a, int *b) {
    if (a == b) {
        return;
    }
    *a ^= *b;
    *b ^= *a;
    *a ^= *b;
}

int main(void) {
    int num1 = 5;
    int num2 = 10;

    printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);
    swapXor(&num1, &num2);
    printf("After swapping: num1 = %d, num2 = %d\n", num1, num2);

    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

After swapping, the first variable holds what the second used to hold, and the second holds what the first used to hold. If you start with 5 and 10, you end with 10 and 5.
If you write a = b first, you lose the old value of a before you can copy it into b. A spare box called temp remembers the first value while you move things around.
Plain integers are passed by value: the function would only swap its own copies. Pointers tell C where the original variables live in memory, so the caller sees the change.
Yes. Example 3 on this page uses XOR for integers. Add/subtract patterns also exist but can overflow. Learn the temp version first, then treat XOR as a puzzle trick, not your everyday style.
Each swap is a few assignments: constant time O(1) and constant extra space for one integer.
Swapping 7 and 7 still works; nothing visible changes. With XOR tricks, some edge cases need extra care, which is another reason beginners prefer temp.

🔄 Input / output examples

Each sample prints two lines (before and after). Replace the literals or use scanf("%d %d", &num1, &num2); for interactive input.

num1, num2 (before)After swap
5, 1010, 5
0, 33, 0
-4, 2020, -4
7, 77, 7

Edge cases

Most mistakes come from forgetting why pointers exist, or from “clever” swaps that overflow.

Copies

void swap(int x, int y)

Swaps only the local copies; main never changes. Use pointers or do the swap directly in main.

Order

Never start with a = b alone

You lose the original a and cannot recover it for b without a saved copy.

Overflow

Arithmetic swaps

Adding two large signed integers can overflow undefined behavior in C. Stick to temp unless you control the range.

XOR

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

VersionTimeExtra 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 trickO(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 *a so you edit the caller’s variables.
  • Extras: Example 3 shows XOR without temp; add/subtract exists too—temp stays the readable default.
Did you know?

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 to a computer.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful