Functions and the Stack
Declaring functions, and why C always passes arguments by value.
What you'll learn
- Declare a function with typed parameters and a return type
- Explain how local variables and function calls use the call stack
- Predict that modifying a plain parameter inside a function never affects the caller's variable
Explanation
A C function declares its return type, name, and typed parameters: int square(int n) { return n * n; }. If a function returns nothing, its return type is void.
Each time a function is called, the program allocates a fresh block of memory on the call stack for that call's local variables and parameters -- often called a stack frame. When the function returns, its stack frame is discarded, and any local variables inside it cease to exist. This is why a function can't return the address of one of its own local variables and expect it to remain valid -- that memory is gone the instant the function returns.
C is strictly pass-by-value: when you call a function with an argument, the function receives its own independent copy of that value in its own stack frame. Modifying a plain parameter inside the function changes only that local copy -- the caller's original variable is completely unaffected. This matters a lot in C specifically because, unlike some higher-level languages, there's no hidden reference-passing happening behind the scenes for ordinary variables; if you want a function to modify the caller's variable, you must explicitly pass a pointer to it (covered in a later lesson).
Guided lab
Predict: Pass-by-value in action
Read this program and predict exactly what it prints.
#include <stdio.h>
int square(int n) {
return n * n;
}
void tryToModify(int x) {
x = 100;
}
int main(void) {
int value = 5;
printf("Square of 5: %d\n", square(value));
tryToModify(value);
printf("Value after tryToModify: %d\n", value);
return 0;
}Stuck? Get a hint.
Common mistakes
- Assuming that modifying a plain (non-pointer) parameter inside a function will change the caller's original variable -- it never does in C.
- Returning the address of a local variable from a function, not realizing that variable's stack frame is gone the moment the function returns.
- Forgetting to declare a function's return type as `void` when it doesn't return a value, instead accidentally omitting a return type altogether.
Knowledge check
Takeaway
C functions receive independent copies of their arguments (pass-by-value), and a function's local variables vanish the instant it returns, since its stack frame is discarded.
Summary
Functions declare typed parameters and a return type; each call gets its own stack frame; plain arguments are always passed by value, never by reference.
References
Your notes
Notes save automatically.
Finished this lesson?
Mark it complete to track your progress and schedule a future review.
AI tutor
The optional AI tutor isn't enabled in this deployment. All lessons, exercises, quizzes, and search work fully without it.