← Exercises|

Repair: the swap that does nothing

Repair9 of 14 · about 7 min

Repair: the swap that does nothing

C passes arguments by value, always. A function receives a COPY of what you gave it, so changing a parameter changes the copy and nothing else. There is no exception to this rule.

To let a function change something of yours, hand it the address instead: &x is "where x lives", and the parameter type becomes int *. Inside, *p means "the thing at that address".

This is not a special case for swap — it is how every C function that modifies its caller works, including the whole standard library.

Example

void add_one(int *n) {
    *n += 1;          /* change what n points at */
}

int value = 5;
add_one(&value);      /* pass the address */
/* value is now 6 */

Your task

This swap function runs, prints nothing wrong, and changes nothing. Make it actually swap the caller's variables. You will need to change the function and the call.

  • ·Pass the addresses of x and y (the & operator)

Stuck?

Explain it

The broken version compiles with no warning at all. Why is that reasonable of the compiler?

Not graded — this is for you.

Where this goes

Project 5 is about the stack: what a call frame holds, what dies when a function returns, and why an address has to be passed for anything to survive. This is the smallest version of that idea.