5.1Functions and call by value
The idea
In C every argument is passed by value: the function works on a copy.
Think of it like this: You hand someone a photocopy of a form; whatever they write on it never reaches your original.
Why it exists
This is why swap(x, y) written naively does nothing, and a favourite way to hide the true output.
How it works
- The call copies each argument into the new parameter variable.
- The function may change its parameters freely.
- When it returns, the copies disappear and the caller's variables are as before.
- Only the return value (also a copy) comes back.
Worked example: swap(x, y) with int parameters
Inside swap, a and b exchange values, but x and y in main still hold 1 and 2. main prints 1 2.
Now play with it
- →Run swap fails and watch the two stack frames: main's x, y and swap's a, b.
- →Run the two calls program and compute y then x by hand first.
swap changes its own copies a and b. x and y in main are untouched.
1#include <stdio.h>2void swap(int a, int b) {3 int t = a;4 a = b;5 b = t;6}7int main() {8 int x = 1, y = 2;9 swap(x, y);10 printf("%d %d\n", x, y);11 return 0;12}
The gold line is the statement about to run.
Call stack (top first)
Output
Check yourself
int f(int x) { x = x + 1; return x; } and int n = 3; f(n); What is n afterwards?
Exam notes (the dense version)
C passes every argument by value: the function gets a copy, so assigning to a parameter never changes the caller's variable. A function needs a prototype or definition before use. A non-void function that reaches its end without return gives an undefined value.
Previous year questions: Functions & Recursion (11)
PYQs are grouped by topic, so this is the full set for Functions & Recursion; try the ones that match this subtopic. Open all 11 on the topic page.