1  Function

  Programming languages make functions easy to maintain and write by giving each function its own section of memory to operate in.

  For example, suppose you have the following function. 

1   int pickMin( int x, int y, int z ) {
2      int min = x ;
3      if ( y < min )
4         min = y ;
5      if ( z < min )
6         min = z ;
7      return min ;
8    }

  You declare parameters xy, and z. You also declare local variables, min. You know that these variables won't interfere with other variables in other functions, even if those functions use the same variable names.

  In fact, you also know that these variables won't interfere with separate invocations of itself.

  

2  Stacks and functions

  Imagine we're starting in main() in a C program. The stack looks something like this

    

  Suppose, inside of body of main() there's a call to foo(). Suppose foo() takes two arguments. One way to pass the arguments to foo() is through the stack. Thus, there needs to be assembly language code in main() to "push" arguments for foo() onto the the stack. 

    

  Once we get into code for foo(), the function foo() may need local variables, so foo() needs to push some space on the stack. 

  We've added a new pointer called FP which stands for frame pointer. The frame pointer points to the location where the stack pointer was, just before foo() moved the stack pointer for foo()'s own local variables.

    

  When exit foo() the stack looks just as it did before we pushed on foo()'s stack frame, except this time the return value has been filled in.

    

  Once main() has the return value, it can pop that and the arguments to foo() off the stack.

    

posted on 2015-05-08 15:40  mengdie  阅读(174)  评论(0编辑  收藏  举报