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?
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.
This is a teaching runtime for a subset of C, running in your browser on a 32-bit model machine. It reports mistakes a real compiler lets through — reading uninitialised memory, running off an array, signed overflow — and it is not the compiler your project uses.
Press Run to see what your program does, or Check when you think it is right. Everything runs here in your browser.