Open In App

Function Call Stack in C++

Last Updated : 22 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

C++ is a procedural and object-oriented language where functions are essential for controlling the program’s flow. When a function is invoked, control shifts to that function, executes its statements, and finally returns to where it was called from. To manage this process smoothly, C++ relies on a special data structure known as the call stack.

What is the Call Stack?

The C++ is a procedural and object-oriented language where functions are essential for controlling the program’s flow. When a function is invoked, control shifts to that function, executes its statements, and finally returns to where it was called from. To manage this process smoothly, C++ relies on a special data structure known as the call stack.

Each time a function is called, the program pushes certain information onto this stack to keep track of where to return once the function is done.

What Does the Call Stack Store?

Whenever a function is called in C++, memory is needed for:

  • Function Parameters: The values passed to the function.
  • Local Variables: Variables declared within the function.
  • Return Address: The location in code to go back to after the function finishes.

All this information forms a stack frame (also called an activation record), which is pushed onto the call stack when the function is called.

A stack pointer (SP) keeps track of the top of the stack, ensuring efficient memory management during function calls and returns. When the function completes, its stack frame is popped from the stack, and control returns to the stored return address.

Example

Let’s look at a simple example to see how functions interact with the call stack:

C++
#include <iostream>
using namespace std;

void D() {
    float d = 40.5f;
    cout << "In function D\n";
}

void C() {
    double c = 30.5;
    cout << "In function C\n";
}

void B() {
    int b = 20;
    C();
    cout << "In function B\n";
}

void A() {
    int a = 10;
    B();
    cout << "In function A\n";
}

int main() {
    A();
    D();
    return 0;
}

Output
In function C
In function B
In function A
In function D

The below images show how this program is stored in the call stack and how it is executed.


Article Tags :
Practice Tags :

Similar Reads