Sams Teach Yourself C++ in 21 Days

(singke) #1
Organizing into Functions 133

5



  1. All the arguments to the function are placed on the stack.

  2. The instruction now in the instruction pointer is executed, thus executing the first
    instruction in the function.

  3. Local variables are pushed onto the stack as they are defined.
    When the function is ready to return, the return value is placed in the area of the stack
    reserved at step 2. The stack is then popped all the way up to the stack frame pointer,
    which effectively throws away all the local variables and the arguments to the function.
    The return value is popped off the stack and assigned as the value of the function call
    itself, and the address stashed away in step 1 is retrieved and put into the instruction
    pointer. The program thus resumes immediately after the function call, with the value of
    the function retrieved.
    Some of the details of this process change from compiler to compiler, or between com-
    puter operating system or processors, but the essential ideas are consistent across envi-
    ronments. In general, when you call a function, the return address and the parameters are
    put on the stack. During the life of the function, local variables are added to the stack.
    When the function returns, these are all removed by popping the stack.
    In coming days, you will learn about other places in memory that are used to hold data
    that must persist beyond the life of the function.


Summary ..............................................................................................................


Today’s lesson introduced functions. A function is, in effect, a subprogram into which
you can pass parameters and from which you can return a value. Every C++ program
starts in the main()function, and main(), in turn, can call other functions.
A function is declared with a function prototype, which describes the return value, the
function name, and its parameter types. A function can optionally be declared inline. A
function prototype can also declare default values for one or more of the parameters.
The function definition must match the function prototype in return type, name, and
parameter list. Function names can be overloaded by changing the number or type of
parameters; the compiler finds the right function based on the argument list.
Local function variables, and the arguments passed in to the function, are local to the
block in which they are declared. Parameters passed by value are copies and cannot
affect the value of variables in the calling function.
Free download pdf