Chapter 5: Functions I

Chapter Goals

Functions as Black Boxes


Writing Functions (Function Definition)

 Let us compute the value of a saving account with an initial balance of $1000 after 10 years with the interest rate of p percent (compound interest).

Writing Functions (futval.cpp)

Syntax 5.1: Function Definition

Syntax 5.1 : Function Definition

return_type function_name(parameter1, ..., parametern)
{
statements
}
Example:
double abs(double x)
{ if (x >= 0) return x;
else return -x;
}
Purpose: Define a functions and supply its implementation.

Writing Functions (Hard Wired Values)

double future_value(double initial_balance, double p, int n)
{ double b = initial_balance * pow(1 + p / 100, n);
return b;
}
double balance = future_value(1000, rate, 10);

Function Comments

 /**
Computes the value of an investment with compound interest.
@param initial_balance - the initial value of the investment
@param p the interest rate per period in percent
@param n the number of periods the investment is held
@return the balance after n periods
*/
double future_value(double initial_balance, double p, int n)
{ double b = initial_balance * pow(1 + p / 100, n);
return b;
}

Syntax 5.2: return Statement

Syntax 5.3 : return statement

 return expression;
Example:
 return pow(1 + p / 100, n);
Purpose: Exit a function, returning the value of the expression as the function result.

Return Values

Return Values (approx.cpp)


Parameters


Side Effects


Procedures

Procedures (printime.cpp)


Reference Parameters

Syntax 5.4: Reference Parameters

Syntax 5.4 : Reference Parameters

 type_name& parameter_name
Example:
 Employee& e
int& result
Purpose: Define a parameter that is bound to a variable in the function call, to allow the function to modify that variable.

Reference Parameters (raisesal.cpp)

Syntax 5.5: Constant Reference Parameters

Syntax 5.5 : Constant Reference Parameters

 const type_name& parameter_name
Example:
 const Employee& e
Purpose: Define a parameter that is bound to a variable in the function call, to avoid the cost of copying the variable into the parameter variable.