Why My Swap Never Worked

Every C student writes this function. Every C student watches it do absolutely nothing. I did. You did. It is a tradition.

void swap(int a, int b) {
    int tmp = a;
    a = b;
    b = tmp;
}

int main(void) {
    int x = 1, y = 2;
    swap(x, y);
    printf("%d %d\n", x, y);   // 1 2. Nothing. Not a thing.
}

It fails because of a rule C never, ever bends: a function gets copies. You call swap(x, y), the program makes two brand new variables, a and b, puts copies of 1 and 2 in them, and hands those over. The function swaps the copies. Does a great job. Then it returns, the copies get thrown in the garbage, and x and y were never touched. Never even met them.

You cannot stop the copying. Don’t try. What you do is copy something that still points home.

void swap(int *a, int *b) {
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

int main(void) {
    int x = 1, y = 2;
    swap(&x, &y);
    printf("%d %d\n", x, y);   // 2 1. Now we're talking.
}

Now the function gets copies of two addresses. A copied address is just as good as the original. Same house number, same house. So when it writes *a = *b, it is writing into x itself, back in main, through the front door it was given.

This is why scanf wants &n and not n. It has to put a value into your variable, and the only way to reach somebody else’s variable is to be told where it lives. Every library function asking for an ampersand is asking for exactly this.

The pattern is bigger than swap. A function that needs to change something that belongs to its caller takes a pointer. A function that only needs to look takes the value. Read the signature and you know its intentions. Very useful. Like reading a contract.