Chapter 5: Functions II

Lecture Goals

Parameters (Review)

Example:
void raise_salary(Employee& e, double by)  // function definition
{
double new_salary = e.get_salary() * ( 1 + by / 100);
e.set_salary(new_salary);
}
int main()
{ Employee harry("Hacker, Harry", 45000.00);
raise_salary(harry, 5); // function call
cout << "New salary: " << harry.get_salary() << "\n";
return 0;
}
parameter variable
reference parameter
constant reference parameter
new variable, copying
reference to an existing variable
constant reference to a value
input parameter
may be input and should be output parameter
input parameter
can modify the parameter (bad style)
should modify the parameter cannot modify the parameter
can be bound to any expression
must be bound to the variable
can be bound to any expression

[raisesal.cpp]

Variable Scope and Global Variables (Variable Scope)

Variable Scope and Global Variables (global.cpp)


Stepwise Refinement


From Pseudocode to Code

Example: Write a function that turns a number into a text string, for example 274 turns into "two hundred seventy four".

From Pseudocode to Code (intname.cpp)


Walkthroughs

int_name(416)
c
r
416
""
int_name(416)
c
r
416
""
 
digit_name(4)
Returns "four"

int_name(416)
c
r
 416 
 "" 
16
"four hundred"

int_name(416)
c
r
 416 
 "" 
 16 
 "four hundred" 
0
"four hundred sixteen"

Preconditions

Syntax 5.6 : Assertions

 assert(expression);
Example:
 assert(x >= 0);
Purpose: If the expression is true, do nothing. If the expression is false, terminate the program, displaying the file name, line number, and expression.