Stack Usage in Function Calls
Stack Usage in Function Calls
Function Calls
A detailed explanation with a stack
diagram example
Program Code Example
void funcB(int x) {
int y = x + 10;
printf("%d", y);
}
void funcA() {
int a = 5;
funcB(a);
}
int main() {
funcA();
return 0;
}
Stack Before Execution
• The stack is empty before the `main()`
function starts.
Stack After `main()` is Called
• Stack Frame - `main`:
• - Return Address: To OS
• Explanation:
• The stack initializes with a frame for `main`,
storing its return address.
Stack After `funcA()` is Called
• Stack Frame - `funcA`:
• - Return Address: To `main`
• - Variable: a = 5
• Explanation:
• `funcA` creates a new stack frame with its
local variable `a` and the return address.
Stack After `funcB()` is Called
• Stack Frame - `funcB`:
• - Return Address: To `funcA`
• - Variable: x = 5
• - Variable: y = 15
• Explanation:
• `funcB` pushes a stack frame with its
parameters, local variable `y`, and return
address.
Stack After `funcB()` Completes
• Stack Frame - `funcA`:
• - Return Address: To `main`
• - Variable: a = 5
• Explanation:
• After `funcB` completes, its stack frame is
popped, and control returns to `funcA`.
Stack After Execution Completes
• Final Stack State:
• - The stack is empty.
• Explanation:
• Once all functions complete, the stack is
emptied, and control returns to the OS.
Key Takeaways
• - The stack uses Last In, First Out (LIFO).
• - Each function call creates a new stack frame.
• - Frames are popped when functions return,
restoring control.