How a Function Call Works
See GeometricSeries.cpp Demo
Steps in call of function g() from function f()
- If necessary (i.e, g() doesn't return void), allocate a slot for g's
result in f's stack frame.
- Push a new stack frame for g with slots for all formal
parameters, local variables, and where to return to.
- For each actual parameter, copy its value into the
corresponding formal parameter.
- Initialize local variables as necessary.
- Execute code for g. f waits for g to finish at this point.
- When return statement is executed, copy
the value of the expression to the slot created for it in f's stack frame.
- Return control to the place in f specified in g's stack frame.
- Pop g's stack frame.
Notes:
- 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.
- All formal and local variables are fresh copies. They
have nothing to do with other variables having the same name elsewhere
in your program.
- See binomial.ccp Demo
- Variables k,n in choose() are distinct from k,n in main().
- Variable n in factorial() is distinct also.
- Copying values of actuals into formals is known as
call by value. Again, assigning to formal variables
does not change value of actual variables.
- We can also have functions with no parameters. For example:
int bozo(); //prototype
...
int i;
i = bozo(); //typical call
- Actual variables are expressions, not necessarily
variables, in call by value.
- 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
- 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.
- The scope of a formal parameter is the body of its function.
int bozo(int a, int b)
{
///// scope of a,b /////
}
- 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
}
- Otherwise, the scope of a variable is everything following
its declarations and within the braces around it.
- 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