Chapter 5: Functions I

Chapter Goals

Functions as Black Boxes

function parameter
sqrt(x) variable
sqrt(2.5) constant
sqrt(x+1.02) expression
function number of
parameters
sqrt(x) 1
pow(x,y) 2
p.get_x() 0

member-function implicit parameter implicit parameter type
harry.get_salary() harry Employee
t.add_seconds(10) t Time
msg.move(dx,dy) msg Message
function return value
sqrt(x) double type
c.get_center() Point type
m.get_text() string type
getline(cin,s) no return value
function
requirements for parameters
fabs(w) the parameter w must be double type, constant or variable
t.second_from(t1) the parameter t1 must be an object from Time class, constant or variable
getline(cin,s) the first parameter must be cin, the second parameter must be a variable of  the type string

Writing Functions (Function Definition)

Writing Functions



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;
}

Return Values

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 (approx.cpp)


Parameters


Side Effects


Procedures

Procedures (printime.cpp)


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

 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.