Presentation is loading. Please wait.

Presentation is loading. Please wait.

Digression: the “Stack” 1 CS502 Spring 2006 Digression: the “Stack” Imagine the following program:– int factorial(int n){ if (n <= 1) return (1); else.

Similar presentations


Presentation on theme: "Digression: the “Stack” 1 CS502 Spring 2006 Digression: the “Stack” Imagine the following program:– int factorial(int n){ if (n <= 1) return (1); else."— Presentation transcript:

1 Digression: the “Stack” 1 CS502 Spring 2006 Digression: the “Stack” Imagine the following program:– int factorial(int n){ if (n <= 1) return (1); else int y = factorial(n-1); return (y * n); } Imagine also the caller:– int x = factorial(100); What does compiled code look like?

2 Digression: the “Stack” 2 CS502 Spring 2006 Compiled code: the caller int x = factorial(100); Put the value “100” somewhere that factorial can find Put the current program counter somewhere so that factorial can return to caller Provide a place to put the result, so that caller can find it

3 Digression: the “Stack” 3 CS502 Spring 2006 Compiled code: factorial function Save the caller’s registers somewhere Get the argument n from the agreed upon place Set aside some memory for local variables and intermediate results – i.e., y, n - 1 Do whatever it was programmed to do Put the result where the caller can find it Restore the caller’s registers Transfer back to the program counter saved by the caller

4 Digression: the “Stack” 4 CS502 Spring 2006 Question: Where is “somewhere”? So that caller can provide as many arguments as needed (within reason)? So that called routine can decide at run-time how much temporary space is needed? So that called routine can call any other routine, potentially recursively?

5 Digression: the “Stack” 5 CS502 Spring 2006 Answer: a “Stack” Stack – a linear memory structure in which items are added and removed in last-in, first-out order. Calling program Push arguments, return address onto stack After return, pop result off stack

6 Digression: the “Stack” 6 CS502 Spring 2006 “Stack” (continued) Called routine Push registers onto stack Push temporary storage space onto stack Do work of the routine Pop registers and temporary storage off stack Leave result on stack Return to program counter left by calling routine

7 Digression: the “Stack” 7 CS502 Spring 2006 Stack (continued) Definition: context – the region of the stack that provides the execution environment of (a particular call to) a function Implementation Usually, a linear piece of memory and a stack pointer in a register Occasionally, a linked list Recursion Stack discipline allows multiple contexts for the same function in the stack at the same time


Download ppt "Digression: the “Stack” 1 CS502 Spring 2006 Digression: the “Stack” Imagine the following program:– int factorial(int n){ if (n <= 1) return (1); else."

Similar presentations


Ads by Google