code and data that performs some subtask of the overall task of the program.

chief technique to deal with complexity of software: decompose problem into subproblems.

Function as a module that can be plugged in anywhere needed in same program or in different programs.

Definition: the code and local data declarations of the function.

Prototype: tells compiler number and types of arguments and the return type. Put at top of program; then compiler can check that each call of the function is correct syntactically (correct number of args, types compatible or converts them). Required in C++. Trivial to do: is just copy of first line of function's definition, names of arguments not needed. Is a statement, so semicolon needed.

Call: invoking/using/calling the function

Built-in functions (islower, sqrt, etc) definition was done by compiler writers, now in machine code form in the standard library. Prototypes are in the header files (which is why you include them). For your own functions, you write the definition and put a prototype at top of program.

Ex. integer exponentiation function:  x to the n (multiply x by itself n times)

Prototype:  int power(int,int)
Args are the x and the n.  Return value is x to the nth power.

Want: table of powers of 2 and 3
 i	2i	3i
 1	2	3
 2	4	9
 3	8      27
 4     16      81

Assume have the power function, use it (ie. call it):
for (i=1; i<=num_rows; i++)
  cout << i << power(2,i) << power(3,i) << endl;


int power (int x, int n) {

  int i, p=1;

  for (i=1; i<=n; i++)
    p = p * x;

  return p;

return type of our power function is int.

function name is an identifier. Must obey rules for identifiers.

x and n are the formal arguments. Can be used as local variables in the body of the function. Are assigned the values of the actual arguments in the call. Values of the actual arguments are passed in to become the values of the formal arguments. Changing the formal arguments will not change the actual arguments in the call of the function.

i and p are local variables of the function. They are not accessible by other functions, including main. They come into existence each time the function is called. They do not keep their values from the last call of the function. The formal arguments are essentially local variables that are initialized by the actual arguments.

return statement is the value returned by/from the function. Typically the last statement in a function, but could have more than one in a function. When executed the function is finished.

Prototype: copy of first line of function definition, without names of the formal args.

int power(int,int);

power.cpp Try it

Next (scope rules)

©David Wills