c / c-fundamentals
15 mins
C Level 3: Function Declarations & Stack Frames
Why This Matters: Functions push call stack frames onto memory. Understanding function scope is essential for stack management.
## Function Prototypes & Call Stack
Functions break programs into modular units. In C, functions must be declared before invocation.
```c
int multiply(int x, int y); // Prototype
int main() {
int res = multiply(4, 5);
return 0;
}
int multiply(int x, int y) {
return x * y;
}
```
MENTAL MODEL & MEMORY LAYOUT
CALL STACK MEMORY: ┌──────────────────────────┐ │ multiply(x=4, y=5) Frame │ ◄── Top of Stack ├──────────────────────────┤ │ main() Stack Frame │ └──────────────────────────┘
COMMON PITFALLS TO AVOID
- Calling a function before declaring its prototype.
- Assuming local variables persist after function returns.
Recursive Call Stack
#include <stdio.h>
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
int main() {
printf("5! = %d\n", factorial(5));
return 0;
}Pushes call stack frames down to base case n <= 1, then unwinds returns.
CONCEPT MASTERY CHECKPOINT
What happens to local variables declared inside a function when the function returns?
NEXT RECOMMENDED LESSON
C Level 4: Arrays & Strings
Challenge: Define a C function `int square(int n)` returning the square of n.