Function Call Stack in Action

Now let’s consider how the call stack supports the operation of a square function called by main (lines 9–14 of Fig. 6.13). First the operating system calls main—this pushes an activation record onto the stack (shown in Fig. 6.14). The activation record tells main how to return to the operating system (i.e., transfer to return address R1) and contains the space for main’s automatic variable (i.e., a, which is initialized to 10).


 1   // Fig. 6.13: fig06_13.cpp
 2   // square function used to demonstrate the function
 3   // call stack and activation records.
 4   #include <iostream>
 5   using namespace std;
 6
 7   int square( int ); // prototype for function square
 8
 9   int main()
10   {
11      int a = 10; // value to square (local automatic variable in main)
12
13      cout << a << " squared: " << square( a ) << endl; // display a squared
14   } // end main
15
16   // returns the square of an integer
17   int square( int x ) // x is a local variable
18   {
19      return x * x; // calculate square and return result
20   } // end function square


10 squared: 100


Fig. 6.13. square function used to demonstrate the function call stack and activation records.

Image

Fig. 6.14. Function call stack after the operating system invokes main to execute the program.

Function main—before returning to the operating system—now calls function square in line 13 of Fig. 6.13. This causes a stack frame for square (lines 17–20) to be pushed onto the function call stack (Fig. 6.15). This stack frame contains the return address that square needs to return to main (i.e., R2) and the memory for square’s automatic variable (i.e., x).

Image

Fig. 6.15. Function call stack after main invokes square to perform the calculation.

After square calculates the square of its argument, it needs to return to main—and no longer needs the memory for its automatic variable x. So square’s stack frame is popped from the stack—giving square the return location in main (i.e., R2) and losing square’s automatic variable. Figure 6.16 shows the function call stack after square’s activation record has been popped.

Image

Fig. 6.16. Function call stack after function square returns to main.

Function main now displays the result of calling square (Fig. 6.13, line 13). Reaching the closing right brace of main causes its stack frame to be popped from the stack, gives main the address it needs to return to the operating system (i.e., R1 in Fig. 6.14)—at this point, main’s automatic variable (i.e., a) no longer exists.

You’ve now seen how valuable the stack data structure is in implementing a key mechanism that supports program execution. Data structures have many important applications in computer science.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.81.223