How a Function Call Works

See GeometricSeries.cpp Demo

Steps in call of function g() from function f()
  1. If necessary (i.e, g() doesn't return void), allocate a slot for g's result in f's stack frame.
  2. Push a new stack frame for g with slots for all formal parameters, local variables, and where to return to.
  3. For each actual parameter, copy its value into the corresponding formal parameter.
  4. Initialize local variables as necessary.
  5. Execute code for g. f waits for g to finish at this point.
  6. When return statement is executed, copy the value of the expression to the slot created for it in f's stack frame.
  7. Return control to the place in f specified in g's stack frame.
  8. Pop g's stack frame.
Notes:
  1. Formal variables are local variables but they are initialized to the values of the actuals. You can store into them in your function code but the values of the actuals are unaffected.
  2. All formal and local variables are fresh copies. They have nothing to do with other variables having the same name elsewhere in your program.
  3. Copying values of actuals into formals is known as call by value. Again, assigning to formal variables does not change value of actual variables.
  4. We can also have functions with no parameters. For example:
            int bozo();       //prototype
            ...
            int i;
            i = bozo();       //typical call
    
  5. Actual variables are expressions, not necessarily variables, in call by value.
  6. The called function must end by returning a value to the caller function via a return statement (unless it is a void function).

Scope

Scope is the part of a program in which a variable or function is known.

General Rules
  1. The scope of a function name is everywhere in the file after the first time its header appears. If you put prototypes for all functions before definitions of any of the functions, they will all be known anywhere you call them.
  2. The scope of a formal parameter is the body of its function.
             int bozo(int a, int b)
             {
               ///// scope of a,b /////
             }
  3. The scope of a variable declared in a for-loop header consists of the header and the loop body.
             for (int i = ....) {         <-- header
               body                       <-- & body
             }
  4. Otherwise, the scope of a variable is everything following its declarations and within the braces around it.
  5. The scope as defined in rules 1-4 above is superceeded by an inner definition of an identifier with the same name.
To Index Previous Next