- Why a swap function that takes plain
intparameters cannot change the caller's variables - How passing
&aand&blets the callee write back to the caller - How the
*operator is used on both sides of=to read and write through pointers - Why a temporary variable is still required even when using pointers
- A common "swap the pointers, not the values" mistake and why it fails
Why a Plain Swap Function Fails
Suppose you write a function that looks like it should swap:
void swap(int x, int y) {
int t = x;
x = y;
y = t;
}
If you call swap(a, b) with a = 3 and b = 7, nothing changes in main. The reason is C's pass-by-value rule: the function receives copies of a and b, not the originals. The swapping happens inside the copies, which are discarded when the function returns. The caller never sees the changes.
This is the classic trap. Many beginners conclude that C "doesn't work" for swap, or that they must return something. Neither is right. C can modify the caller's variables — you just have to give it the variables' addresses instead of their values.
💡 In one line: Pass-by-value copies the values. Pass-by-address passes the addresses, so writing through the pointer reaches the original variable.
How Pointers Fix It
Instead of passing a and b, pass &a and &b. The function's parameter type changes to int *, so it accepts addresses. Inside the function, *x and *y refer to the caller's variables, not to copies. Writing to *x writes to a in the caller.
| Style | Function signature | Call | Affects caller? |
|---|---|---|---|
| Pass-by-value | void swap(int x, int y) | swap(a, b); | No — copies only |
| Pass-by-address | void swap(int *x, int *y) | swap(&a, &b); | Yes — original variables are changed |
A common misconception is that "C passes arrays by reference." It doesn't — arrays decay to pointers when passed, and that is why functions can modify array contents. The mechanism is exactly the same as this program: a pointer is passed by value, but the pointer's value is an address, and writing through the address reaches the array.
Complete C Program
Program: swap two numbers using pointers, then verify the caller sees the change
#include <stdio.h>
/* Declare the swap function — takes two int pointers */
void swap(int *x, int *y);
int main(void) {
int a = 3;
int b = 7;
printf("Before swap: a = %d, b = %d\n", a, b);
/* Pass the ADDRESSES of a and b */
swap(&a, &b);
printf("After swap : a = %d, b = %d\n", a, b);
return 0;
}
/* --- The swap function --- */
void swap(int *x, int *y) {
/* Guard against NULL to avoid a crash */
if (x == NULL || y == NULL) {
return;
}
int temp = *x; /* save the value behind x */
*x = *y; /* write y's value into x's target */
*y = temp; /* write the saved value into y's target */
}
Program Output
Before swap: a = 3, b = 7
After swap : a = 7, b = 3
The two values have been exchanged. a now holds 7 and b holds 3 — even though both assignments were made inside swap, which is a different function with its own frame. The change is visible in main because the writes went through pointers to main's variables.
Step-by-Step Explanation
Let's trace the program frame by frame.
1. int a = 3; int b = 7;
main's frame now contains two integers: a (3) and b (7). Each has its own address. Suppose, for illustration, &a = 0x1000 and &b = 0x1004. The exact values will differ per run.
2. swap(&a, &b);
The & operator yields the addresses of the caller's variables. swap receives x = 0x1000 and y = 0x1004. Note that x and y are pointer variables in swap's frame, holding the caller's addresses. Inside swap, *x refers to a in the caller, and *y refers to b in the caller.
3. int temp = *x;
*x reads whatever is stored at the address in x. Since x points at the caller's a, this reads 3 and stores it in temp. The temp variable is crucial — without it, the next step would clobber the value we still need.
4. *x = *y;
The right side reads *y, which is b's value (7). The left side is a write target: *x means "the memory that x points at," which is a in the caller. So the caller's a is overwritten with 7. Now both a and b in the caller hold 7, but temp still has 3.
5. *y = temp;
*y is a write target: the memory that y points at, which is b in the caller. Assign temp (3) to it. Now the caller's b holds 3 and a holds 7 — the swap is complete.
6. Why the NULL check?
If a caller accidentally passed NULL, dereferencing it would crash. A quick if (x == NULL || y == NULL) return; turns that crash into a silent no-op — much easier to debug. It also signals to future readers that the function is expected to be given real addresses. In production code you might prefer an assert or returning an int error code, but for a beginner example the early return is clearest.
7. What if I forget to pass &?
If you write swap(a, b), the compiler sees int arguments but the function expects int *. Under -Wall you'll get a warning like "passing argument 1 of 'swap' makes pointer from integer without a cast." If the warning is suppressed and the program runs, swap will treat 3 and 7 as memory addresses and try to write to them, which is undefined behaviour — usually a crash with a segmentation fault. The compiler is doing you a favour: always compile with -Wall -Wextra.
8. Why not "swap the pointers"?
A tempting but wrong idea is:
void bad_swap(int *x, int *y) {
int *t = x;
x = y;
y = t;
}
This swaps the pointers x and y inside bad_swap, but both are local copies of the caller's addresses. Reassigning them has no effect on the caller. Worse, it doesn't change the values those addresses point to. To change the caller's variables, you must write through *x and *y, not reassign x and y.
9. Does this really swap in place, or was there a temporary?
A temporary is unavoidable at the machine level — you cannot exchange two slots in memory without somewhere to hold one value while the first is overwritten. The classic XOR trick (*x ^= *y; *y ^= *x; *x ^= *y;) avoids the extra variable syntactically, but it has subtle problems (it fails if x and y point to the same location, and it confuses optimizers), so it's rarely recommended in production. The temp-variable swap is the clearest and safest form.
10. Does this scale to other types?
Yes — the same pattern works for any type. A void swap_double(double *x, double *y), a void swap_str(const char **x, const char **y), or a void swap_struct(struct foo *x, struct foo *y) all use identical logic. Only the pointed-to type changes; the algorithm and the reasoning are unchanged. That's why mastering this small program pays off across the entire pointer chapter — the pattern reappears everywhere.
🎯 Remember this: The swap function changes the caller's variables because it receives their addresses. The writes happen through *x and *y, not through reassigning x and y. Reassigning a pointer moves the pointer; writing through it modifies the target.
Frequently Asked Questions
1. Why does the plain-int swap version not work?
Because C is pass-by-value. When you call swap(a, b), the compiler copies a and b into the parameters x and y. Any assignment to x or y inside the function affects only those local copies. The caller's a and b are untouched. The pointer version solves this by passing addresses and writing through them.
2. Can I return two values from swap instead?
Not directly — C functions return at most one value. You could pack two ints into a struct and return that, but the caller would still have to assign the result back to its own variables (struct pair r = swap(a, b); a = r.x; b = r.y;). The pointer approach is cleaner and avoids the extra copies. In practice, pointers (or their close cousins, references in C++) are the standard way to "return" multiple values.
3. What if x and y point to the same variable?
The temp-based swap still works: temp = *x saves the value, then *x = *y writes it back to the same place (no change), and *y = temp writes it again (still no change). So swap(&a, &a) is a harmless no-op. The XOR version would zero out the value in that case — a reason to prefer the temp-based swap.
4. Does swap need to know the variables are named a and b?
No. The function works for any pair of int variables — the names a and b are irrelevant. swap(&x1, &y2), swap(&nums[i], &nums[j]), and swap(&config.width, &config.height) all work identically. This generality is a core reason pointers exist: a function should operate on data, not on named variables.
5. Can this swap be inlined or made into a macro?
Yes. Many codebases use a macro like #define SWAP(t, x, y) do { t _t = (x); (x) = (y); (y) = _t; } while (0). This avoids the function call overhead for tight loops, at the cost of macro hygiene headaches. For most beginner work, the function version is clearer and just as fast with optimization enabled. Only reach for the macro if profiling shows the call overhead matters.
6. Why does the compiler complain about swap(a, b)?
The compiler sees int arguments where the function expects int *. Passing an int to a pointer parameter is a type mismatch. Under strict warnings you get "makes pointer from integer without a cast." If you suppress warnings and run anyway, swap will treat small integers like 3 and 7 as memory addresses and try to write to them — undefined behaviour. Always compile with -Wall -Wextra so the compiler catches this before it becomes a runtime disaster.
💡 Tip: Once this program runs, try to break it on purpose. Call swap(a, b) instead of swap(&a, &b) and see what the compiler says. Remove the temp variable and try to do the swap in two lines — you'll see why three assignments are necessary. These small experiments are how the "why" of pointers becomes intuitive.