GCGY Beta v1.0.1
GrowCodeEngineering
← Back to Hub
Back to Topics
c / c-functions
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
Continue Path
Challenge: Define a C function `int square(int n)` returning the square of n.
C Level 3: Function Declarations & Stack Frames
1
2
3
4
5
6
7
8
9
10
11
12
13
No test case execution results available yet. Click "Run Code" to evaluate your solution.