- Why a swap function written with plain
intparameters fails silently - What pass-by-value actually means in terms of memory
- How to use pointers to let a function modify the caller's variables
- The three-line swap:
temp = *a; *a = *b; *b = temp; - Why
swap(&x, &y)passes addresses, not values
Why swapping catches everyone
The swap function is the classic C trap. You want to write a function that takes two numbers and swaps them. You write this:
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
You call it from main, print the results — and nothing has changed. The function ran, the swap logic looks right, but x and y are still in their original positions. Why?
The answer is pass-by-value. When you call swap(x, y), C copies the values of x and y into the function's parameters a and b. Inside the function, a and b are different variables — separate slots of memory — that just happen to hold the same values as x and y. When the function swaps a and b, it's swapping the copies. The originals in main are untouched.
This is one of those things you have to see fail in person to believe. The function looks perfectly correct. The logic is right. But the effect is invisible to the caller. It's the moment the phrase "pass by value" clicks — and it's why the next topic (pointers) is essential, not optional. Without pointers, a function cannot modify any variable in its caller's scope. Ever.
This assignment fixes that. It shows the broken version first, traces it step-by-step, and then writes the working version using pointers. The working version uses pass by reference — a term that means "pass a pointer, and let the function modify what it points to." In C, that's the only way to swap two variables from inside a function. It's also the foundation of every "output parameter" pattern you'll see later (functions that return multiple values through pointer arguments).
💡 In one line: use pointers. Declare void swap(int *a, int *b), implement with int temp = *a; *a = *b; *b = temp;, and call it from main as swap(&x, &y). The & on the call and the * inside the function are what make it work.
The version that doesn't work (and why)
Let's look at the broken version in full, so you can see the failure firsthand:
❌ The broken version — pass by value
#include <stdio.h>
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
int main(void) {
int x = 5, y = 10;
printf("Before: x = %d, y = %d\n", x, y);
swap(x, y);
printf("After: x = %d, y = %d\n", x, y);
return 0;
}
Output:
Before: x = 5, y = 10
After: x = 5, y = 10
The output is identical before and after. The function ran — you can verify with a print statement inside it — but the swap happened to a and b, which are the function's local parameters, not x and y. When swap returns, a and b are destroyed along with the function's stack frame, and their new values disappear with them.
The lesson is: a function that receives plain int parameters cannot modify the caller's variables. It gets copies. Modifying copies has no effect on the originals. This is true for every type — int, float, char, structs, arrays — unless you pass a pointer (or, for arrays, unless you pass an array, which decays to a pointer anyway). Pass by value is deliberate: it protects the caller from unwanted side effects. But when you want side effects (like a swap), you have to opt in by passing addresses.
⚠️ The trap: if the broken version compiles without warnings and produces no obvious error at the call site, you might think it works. It doesn't — it just silently does nothing. That's why the passing of pointers (and the corresponding & at the call site) is essential for this function.
The version that does — with pointers
✅ The correct version — pass by pointer
#include <stdio.h>
/* Function prototype */
void swap(int *a, int *b);
int main(void) {
int x, y;
printf("Enter two integers: ");
scanf("%d %d", &x, &y);
printf("Before swap: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
}
/* Function definition */
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
And here's a version that uses the "swap via XOR" trick — no temporary variable. It works for integers but has edge cases (swapping a variable with itself zeroes it out), so it's more of an interesting exercise than a recommended pattern:
Variant: XOR swap (no temporary variable)
#include <stdio.h>
void swap_xor(int *a, int *b) {
if (a == b) return; /* guard: if both pointers refer to the same variable */
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
int main(void) {
int x, y;
printf("Enter two integers: ");
scanf("%d %d", &x, &y);
printf("Before: x = %d, y = %d\n", x, y);
swap_xor(&x, &y);
printf("After: x = %d, y = %d\n", x, y);
return 0;
}
The XOR swap is a historical curiosity — it was useful when registers were scarce and you wanted to avoid an extra temporary. On modern CPUs, the three-line version with a temporary variable is just as fast (often faster, because the compiler optimizes it well) and is far less error-prone. The if (a == b) return; guard is essential: without it, swap_xor(&x, &x) would zero out x (because x ^= x is 0). Use the temporary version in real code; admire the XOR trick as a curiosity.
And here's a version that works with float — the same pattern, just with a different type:
Variant: swap floats
#include <stdio.h>
void swap_f(float *a, float *b) {
float temp = *a;
*a = *b;
*b = temp;
}
int main(void) {
float x, y;
printf("Enter two floats: ");
scanf("%f %f", &x, &y);
printf("Before: x = %.2f, y = %.2f\n", x, y);
swap_f(&x, &y);
printf("After: x = %.2f, y = %.2f\n", x, y);
return 0;
}
The pattern is identical. Once you've written swap(int*, int*), writing swap_f(float*, float*) is a mechanical substitution. That's the point of this assignment: the pattern of pass-by-pointer is what transfers, not the specific types.
Program Output
A typical run of the pointer version:
Enter two integers: 5 10
Before swap: x = 5, y = 10
After swap: x = 10, y = 5
With negative numbers:
Enter two integers: -7 42
Before swap: x = -7, y = 42
After swap: x = 42, y = -7
With equal numbers (nothing appears to change, but the swap still happened — the values were identical):
Enter two integers: 8 8
Before swap: x = 8, y = 8
After swap: x = 8, y = 8
And for the XOR version:
Enter two integers: 3 7
Before: x = 3, y = 7
After: x = 7, y = 3
The output of the broken version is worth running yourself — it produces the same values before and after, and the reason isn't obvious until you understand pass-by-value. Seeing it fail is more instructive than reading about it failing.
Step-by-Step Explanation
Let's trace through the working version, following the values in memory.
1. Setting up in main
int x, y; creates two integer variables on the stack. Then scanf("%d %d", &x, &y) reads two integers into them. Suppose the user enters 5 10. Now:
xis a variable holding5, at some memory address, say0x1000.yis a variable holding10, at some address, say0x1004(4 bytes later — typical for adjacentints).
2. The call site: swap(&x, &y)
Here's the critical part. The & before x and y takes the addresses of those variables. So the arguments passed are 0x1000 and 0x1004 — not the values 5 and 10. The function receives two pointers, each pointing at one of the caller's variables.
Inside swap, the parameters are int *a and int *b. When swap is called with (&x, &y), the value of a is 0x1000 (it points at x) and the value of b is 0x1004 (it points at y).
3. Inside swap: int temp = *a;
*a means "the value at the address stored in a." That is, "dereference a" — look at the memory that a points to. Since a = 0x1000 and 0x1000 is where x lives, *a is 5. So temp = 5.
4. *a = *b;
*b is the value at address 0x1004, which is where y lives, so *b = 10. *a = *b writes 10 into the memory that a points to — that is, into x in main. Now x holds 10.
5. *b = temp;
temp is 5. *b = temp writes 5 into the memory that b points to — that is, into y. Now y holds 5.
6. After the swap returns
The function's local variables (a, b, temp) are destroyed. But their changes have already been written to memory that survives — x and y in main now hold 10 and 5 respectively. The swap has taken effect. ✓
7. The key insight: addresses, not values
The broken version passed 5 and 10. The working version passes 0x1000 and 0x1004. That's the whole difference. C doesn't have pass-by-reference in the way C++ does — but it doesn't need it, because passing addresses gives the same effect. A pointer is a value (the address of a variable), and passing it by value means the function gets a copy of the address, not a copy of the variable's content. The function then reads and writes through the address, and those reads and writes affect the original variable.
8. Why void as the return type?
swap doesn't need to return anything — its entire purpose is to modify its arguments. The void return type says "this function performs side effects and has nothing to give back." That's the standard idiom for mutating functions in C. You could return a status code (e.g., 0 for success, -1 for error), but for a simple swap, there's nothing meaningful to return.
9. Naming the parameters a and b
Parameter names are local to the function, so they don't clash with x and y in main. Using a and b is conventional, but you could name them left and right, or first and second — anything readable. The * in the declaration (int *a) is what makes them pointers; the name is just a label.
10. Warning for future-you
In swap(int *a, int *b), the parameters are pointer variables. When you write *a = *b, you're writing through the pointer. When you write a = b, you're copying the pointer value — you're not swapping anything. This distinction (pointer vs. value pointed to) is a common source of bugs. The correct swap uses *a and *b (dereferencing) on every line.
🔍 Try this: add a printf("Inside swap: a points to %p, b points to %p\n", (void*)a, (void*)b) at the top of the function, and a similar print in main of &x and &y. Run it, and compare the addresses. They'll be the same — proving the pointers are pointing at the caller's variables, not at copies.
Frequently Asked Questions
1. Why doesn't swap(int a, int b) work?
Because C uses pass by value by default. When you call swap(x, y), C copies the values of x and y into the function's parameters a and b. Those are separate variables in the function's stack frame. Swapping them swaps the copies, and when the function returns, the copies are destroyed. The originals in main are untouched. To modify the caller's variables, you must pass their addresses (pointers) so the function can write through those addresses.
2. What does &x mean at the call site?
&x is the "address of x" — it produces a pointer that holds the memory address where x lives. When you call swap(&x, &y), you're passing the addresses of x and y, not their values. The function's parameters receive these addresses, and by dereferencing them (*a, *b), the function can read and write the caller's variables.
3. What if I pass NULL to swap?
Undefined behavior — swap(NULL, NULL) will crash. The function doesn't check for NULL pointers, and dereferencing a NULL pointer is a segmentation fault. If you need to be defensive, add if (!a || !b) return; at the top of the function. For most uses, the caller has the addresses of actual variables (from &x, &y), so NULL isn't possible — but it's worth knowing that pointers can be NULL and that dereferencing them is unsafe.
4. Can I swap two numbers without a temporary variable?
Yes, using arithmetic (a = a + b; b = a - b; a = a - b;) or XOR (a ^= b; b ^= a; a ^= b;). Both work for integers but have edge cases. The arithmetic version overflows for large values (if a + b exceeds INT_MAX, you get undefined behavior), and the XOR version fails when a and b are the same variable (it zeroes out that variable). The version with a temporary variable is safest and clearest — use it in real code. The XOR and arithmetic versions are useful as exercises in understanding what the swap is doing.
5. Can I swap structures, arrays, or strings the same way?
Structs: yes, same pattern — void swap_struct(struct S *a, struct S *b) { struct S temp = *a; *a = *b; *b = temp; }. Arrays: not directly, because arrays can't be assigned — you'd copy element by element. Strings (as char *): yes, you'd swap the pointers, not the contents — void swap_str(const char **a, const char **b). The pattern generalizes, but the details of what "swap" means depend on the type.
6. Why does the compiler not warn about the broken version?
Because it's not technically an error — swap(int a, int b) is a valid function that does what it says (swaps two int values). It just doesn't have any visible effect on the caller. The compiler can't know that you intended the function to modify caller variables — that's a design choice, and modifying caller variables requires passing pointers, which is your responsibility to do. Modern compilers with -Wall might hint at unused parameters or return values, but the broken version still compiles cleanly. That's why it's such a common trap.
💡 Tip: Once this works, use the swap function inside a sorting routine. Bubble sort, selection sort, insertion sort — all of them need to swap two elements. Try writing a bubble sort that uses your swap function. That's the natural next step, and it demonstrates why the swap pattern is so important: it's not an exercise, it's a building block.