0% found this document useful (0 votes)
8 views9 pages

Stack Usage in Function Calls

The document explains stack usage in function calls using a code example with functions `main`, `funcA`, and `funcB`. It describes how the stack evolves during execution, detailing the creation and removal of stack frames for each function call. Key takeaways include the Last In, First Out (LIFO) nature of the stack and the restoration of control as frames are popped upon function completion.

Uploaded by

jaisri24
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views9 pages

Stack Usage in Function Calls

The document explains stack usage in function calls using a code example with functions `main`, `funcA`, and `funcB`. It describes how the stack evolves during execution, detailing the creation and removal of stack frames for each function call. Key takeaways include the Last In, First Out (LIFO) nature of the stack and the restoration of control as frames are popped upon function completion.

Uploaded by

jaisri24
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Understanding Stack Usage in

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.

You might also like