1 chapter 5: functions chapter goals to be able to program functions and proceduresto be able to...

50
1 Chapter 5: Functions Chapter 5: Functions Chapter Goals Chapter Goals To be able to program functions and To be able to program functions and procedures procedures To become familiar with the concept of To become familiar with the concept of parameter passing parameter passing To recognize when to use value and To recognize when to use value and reference passing reference passing To appreciate the importance of function To appreciate the importance of function comments comments To be able to determine the scope of To be able to determine the scope of variables variables To minimize the use of side effects and To minimize the use of side effects and global variables global variables To develop strategies for decomposing To develop strategies for decomposing complex tasks into simpler ones complex tasks into simpler ones To document the responsibilities of To document the responsibilities of functions and their callers with functions and their callers with preconditions preconditions

Upload: gwendoline-paul

Post on 06-Jan-2018

218 views

Category:

Documents


0 download

DESCRIPTION

3 Functions as Black Boxes  Functions may have input values or parameters that are transferred or passed into the function. The x in y = sqrt(x);The x in y = sqrt(x); Both, the x and the y, in z = pow(x, y);Both, the x and the y, in z = pow(x, y); Could be an expression as inCould be an expression as in sqrt(b * b - 4 * a * c);  Functions may have output or return values. The y in y = sqrt(x);The y in y = sqrt(x);  Both, parameters and return values, are of a particular type explicitly stated in the definition of the function. You cannot compute sqrt("Harry");You cannot compute sqrt("Harry"); You cannot assign string s = sqrt(5.5);You cannot assign string s = sqrt(5.5);

TRANSCRIPT

Page 1: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

11

Chapter 5: Functions Chapter 5: Functions Chapter GoalsChapter Goals

• To be able to program functions and To be able to program functions and procedures procedures

• To become familiar with the concept of To become familiar with the concept of parameter passing parameter passing

• To recognize when to use value and reference To recognize when to use value and reference passing passing

• To appreciate the importance of function To appreciate the importance of function comments comments

• To be able to determine the scope of variables To be able to determine the scope of variables • To minimize the use of side effects and global To minimize the use of side effects and global

variables variables • To develop strategies for decomposing To develop strategies for decomposing

complex tasks into simpler ones complex tasks into simpler ones • To document the responsibilities of functions To document the responsibilities of functions

and their callers with preconditions and their callers with preconditions

Page 2: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

22

Functions as Black BoxesFunctions as Black Boxes

A A functionfunction is a piece of code assigned to a is a piece of code assigned to a name. name. • sqrt() -- computes the square root of a floating sqrt() -- computes the square root of a floating

point number point number • getline() -- reads a line from the stream getline() -- reads a line from the stream

Functions can be thought of as Functions can be thought of as black black boxesboxes • you don't need to know the internals of the you don't need to know the internals of the

code in order to use it properly code in order to use it properly The execution of main() is temporarily The execution of main() is temporarily

suspended while a function is running. suspended while a function is running.

Page 3: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

33

Functions as Black BoxesFunctions as Black Boxes Functions may have Functions may have input valuesinput values or or parametersparameters

that are transferred or that are transferred or passedpassed into the function. into the function. • The x in y = sqrt(x); The x in y = sqrt(x); • Both, the x and the y, in z = pow(x, y); Both, the x and the y, in z = pow(x, y); • Could be an Could be an expressionexpression as in as in

sqrt(b * b - 4 * a * c); sqrt(b * b - 4 * a * c); Functions may have Functions may have outputoutput or or returnreturn valuesvalues. .

• The y in y = sqrt(x); The y in y = sqrt(x); Both, parameters and return values, are of a Both, parameters and return values, are of a

particular type explicitly stated in the definition of particular type explicitly stated in the definition of the function. the function. • You cannot compute sqrt("Harry"); You cannot compute sqrt("Harry"); • You cannot assign string s = sqrt(5.5); You cannot assign string s = sqrt(5.5);

Page 4: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

44

Writing Functions Writing Functions (Syntax 5.1 : Function Definition)(Syntax 5.1 : Function Definition)

General format of Function DefinitionGeneral format of Function Definition<<rettype> <fname> rettype> <fname> ( <( <par1>par1>,...,,..., <parn> <parn>) { ) {

<<statements>statements> // function body// function body……

}} Example:Example:

double abs(double x) { double abs(double x) { if (x >= 0) if (x >= 0) return x; return x; else else return -x; return -x;

} }

Purpose:Purpose: Define a function and supply its implementation. Define a function and supply its implementation.

Page 5: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

55

Function Definition (cont.)Function Definition (cont.) To create a function, we must supply To create a function, we must supply

its name, return type, a list of its name, return type, a list of parameters and their names (if the parameters and their names (if the list of parameters is not empty). list of parameters is not empty). Example:Example: double future_value(double p)double future_value(double p)

For the duration of the execution of For the duration of the execution of the function, a parameter is stored in the function, a parameter is stored in a a parameter variableparameter variable (in this (in this example, p). example, p).

Page 6: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

66

Function Definition (cont.)Function Definition (cont.)

The The bodybody of the function is delimited by braces (just like of the function is delimited by braces (just like main()): main()): Example:Example:

double future_value(double p) { double future_value(double p) { . . . . . .

} } Code is included in its body to perform the computation. Code is included in its body to perform the computation.

The result is returned to the caller function. The result is returned to the caller function. Example:Example:

double future_value(double p) { double future_value(double p) { double b = 1000 * pow(1 + p / 100, double b = 1000 * pow(1 + p / 100,

10); 10); return b; return b;

}}

Page 7: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

77

Writing Functions (futval.cpp)Writing Functions (futval.cpp) 01: 01: #include#include <iostream> <iostream>02: 02: #include#include <cmath> <cmath>03: 03: 04: 04: usingusing namespacenamespace std; std;05: 05: 06: double 06: double future_valuefuture_value(double p) {  (double p) {  08:    double b = 1000 * 08:    double b = 1000 * powpow(1 + p / 100, 10);(1 + p / 100, 10);09:    09:    returnreturn b; b;10: }10: }11: 11: 12: int 12: int mainmain() {  () {  14:    cout << "Please enter the interest rate in percent: ";14:    cout << "Please enter the interest rate in percent: ";15:    double rate;15:    double rate;16:    cin >> rate;16:    cin >> rate;17: 17: 18:    double balance = 18:    double balance = future_valuefuture_value(rate);(rate);19:    cout << "After 10 years, the balance is " 19:    cout << "After 10 years, the balance is " 20:       << balance << "\n";20:       << balance << "\n";21: 21: 22:    22:    returnreturn 0; 0;23: } 23: }

Page 8: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

88

Writing Functions Writing Functions (Hard Wired Values) (Hard Wired Values)

The future_value function in futval.cpp is The future_value function in futval.cpp is flawed because the starting amount of the flawed because the starting amount of the investment and the number of years are investment and the number of years are hard-wiredhard-wired. .

Hard-wiring prevents reuse of functions: Hard-wiring prevents reuse of functions: • Computing the balance after 20 years. Computing the balance after 20 years. • Computing the balance with a different interest Computing the balance with a different interest

rate. rate. We avoid hard-wiring values into functions We avoid hard-wiring values into functions

by passing them in as additional by passing them in as additional parameters. parameters.

Page 9: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

99

Writing FunctionsWriting Functions

Functions are more valuable when Functions are more valuable when they are they are reusablereusable. .

Example: Example: double future_value(double initial_balance, double future_value(double initial_balance,

double p, int n) { double p, int n) { double b = initial_balance * pow(1+p/100, double b = initial_balance * pow(1+p/100,

n); n); return b; return b; } }

Page 10: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

1010

Function CommentsFunction Comments We must comment every function, even if it We must comment every function, even if it

seems silly. seems silly. Comments are for human readers, not compilers.Comments are for human readers, not compilers. There is no universal standard for comment There is no universal standard for comment

layout, but this book uses the layout, but this book uses the javadocjavadoc style. style. • An @param entry explaining each parameter An @param entry explaining each parameter • An @return entry describing the return value An @return entry describing the return value

Comments do not explain implementation, but Comments do not explain implementation, but the the ideaidea. .

Write comments Write comments firstfirst, before writing the function , before writing the function code, to clarify your understanding of what you code, to clarify your understanding of what you need to program. need to program.

Page 11: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

1111

Function Comments Function Comments /** Computes the value of an investment with/** Computes the value of an investment with ** compound interest. ** compound interest. @param intial_balance the initial value of the @param intial_balance the initial value of the

investment investment @param p the interest rate pre period in percent @param p the interest rate pre period in percent @param n the number of periods the investment is @param n the number of periods the investment is

held held @return the balance after n periods @return the balance after n periods */ */ double future_value(double initial_balance, double future_value(double initial_balance,

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

Page 12: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

1212

Return Values Return Values (Syntax 5.2 : return Statement)(Syntax 5.2 : return Statement)

Syntax of the return statement: Syntax of the return statement: returnreturn <expression> <expression>;; Example:Example: return pow(1+p/100, n);return pow(1+p/100, n);

Purpose:Purpose: Exit a function, returning the value Exit a function, returning the value of the expression as the function of the expression as the function

result.result.

Page 13: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

1313

Return Values• When a return statement executed, the

function exits immediately. • Example: double future_value(doubleinitial_balance,double future_value(doubleinitial_balance, double p, int n){double p, int n){ double b; // final balance double b; // final balance    if (n < 0) return 0;if (n < 0) return 0;  if (p < 0) return 0;  if (p < 0) return 0;  b = initial_balance * pow(1+p/100, n);  b = initial_balance * pow(1+p/100, n);  return b;  return b;} }

Page 14: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

1414

ExampleExample int max_val(int x, int y) { int max_val(int x, int y) { int v; // local variableint v; // local variable

if (x > y) if (x > y) v = x; v = x;

else else v = y; v = y;

// v is a copy of largest// v is a copy of largest// value among x and y// value among x and yreturn v; return v;

}}

Page 15: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

1515

Return Value (cont.)Return Value (cont.) It is important that every branch of a It is important that every branch of a

function returns a value. function returns a value. Example:Example: double future_value(double initial_balance,double future_value(double initial_balance,

double p, int n) { double p, int n) { if (p >= 0) if (p >= 0)

return initial_balance*pow(1+p/100, return initial_balance*pow(1+p/100, n); n); /* Error */ /* Error */

}} In this case, one branch does not have return…In this case, one branch does not have return…

Page 16: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

1616

Return Value (cont.)Return Value (cont.) A function that returns a truth value is A function that returns a truth value is

called a called a predicatepredicate. . Example: Example:

bool approx_equal(double x, double y) {bool approx_equal(double x, double y) {    const double EPSILON = 1E-14;    const double EPSILON = 1E-14;    if (x == 0) return fabs(y) <= EPSILON;    if (x == 0) return fabs(y) <= EPSILON;    if (y == 0) return fabs(x) <= EPSILON;    if (y == 0) return fabs(x) <= EPSILON;    return fabs(x-y)/max(fabs(x), fabs(y)) <= EPSILON;    return fabs(x-y)/max(fabs(x), fabs(y)) <= EPSILON; }  }

The expression The expression approx_equal(a, b)approx_equal(a, b) returns returns truetrue iff iff the values of a and b are approximately equal…the values of a and b are approximately equal…

Page 17: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

1717

Example Using the FunctionExample Using the Function……. Prototype and/or definition of the function comes here…. Prototype and/or definition of the function comes here………..21: int 21: int mainmain() {  () {  23:    double x;23:    double x;24:    cout << "Enter a number: ";24:    cout << "Enter a number: ";25:    cin >> x;25:    cin >> x;26: 26: 27:    double y;27:    double y;28:    cout << "Enter another number: ";28:    cout << "Enter another number: ";29:    cin >> y;29:    cin >> y;30: 30: 31:    31:    ifif ( (approx_equalapprox_equal(x, y))(x, y))32:       cout << "The numbers are approximately equal.\n";32:       cout << "The numbers are approximately equal.\n";33:    33:    elseelse34:       cout << "The numbers are different.\n";34:       cout << "The numbers are different.\n";35: 35: 36:    36:    returnreturn 0; 0; 37: }37: }

   

Page 18: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

1818

Parameters Parameters When a function starts, its When a function starts, its parameter variablesparameter variables are initialized with are initialized with

the expressions in the function call. the expressions in the function call.

Example:Example: b = future_value(total/2, rate, year2-year1);b = future_value(total/2, rate, year2-year1);

It is entirely legal to modify the values of the parameter variables It is entirely legal to modify the values of the parameter variables later (in the function body). later (in the function body).

Example:Example: double future_value(double initial_balance, double future_value(double initial_balance,

double p, int n) { double p, int n) { p = 1 + p / 100; p = 1 + p / 100; double b = initial_balance * pow(p, n); double b = initial_balance * pow(p, n); return b; return b;

}}

……Many programmers consider this practice bad style..Many programmers consider this practice bad style..

Page 19: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

1919

Function Declaration (or Prototype) Function Declaration (or Prototype) General syntax for the declaration of a function (prototype): General syntax for the declaration of a function (prototype):

<ret_type> <fname> <ret_type> <fname> ( <( <par1>par1>, ..., <, ..., <parn> parn> ); );

Example:Example: double abs(double x);double abs(double x);

Purpose:Purpose: Declare a function so that it can be called before Declare a function so that it can be called before it is defined.it is defined.

Function declaration resolves compiler confusion Function declaration resolves compiler confusion that can arise when one function calls another. that can arise when one function calls another.

It also makes programs easier to read. It also makes programs easier to read.

Page 20: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

2020

Side Effects Side Effects An externally observable effect of a function is An externally observable effect of a function is

called a called a side effect.side effect. Examples are: Examples are: • Displaying characters on the screen (including error Displaying characters on the screen (including error

messages). messages). • Updating variables outside the functions. Updating variables outside the functions. • Terminating the program. Terminating the program.

A function should leave no trace of its existence A function should leave no trace of its existence except for returning a value. except for returning a value.

Functions that print values become worthless in Functions that print values become worthless in certain situations. certain situations. • Graphics programs that have no output streams. Graphics programs that have no output streams. • Programs where the user's language is not English. Programs where the user's language is not English. • Programs that don't want to print the value! Programs that don't want to print the value!

Ideally,Ideally, a function computes a a function computes a single valuesingle value and and has no other side effect. has no other side effect.

Page 21: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

2121

ProceduresProcedures A function without a return value is called a A function without a return value is called a procedureprocedure. .

Example:Example: print_time(now); print_time(now);

The missing return value is indicated by the keyword void. The missing return value is indicated by the keyword void. Example: Example:

void print_time(Time t) { void print_time(Time t) { cout << t.get_hours() << ":"; cout << t.get_hours() << ":"; if (t.get_minutes() < 10) if (t.get_minutes() < 10) cout << "0"; cout << "0"; cout << t.get_minutes() << ":"; cout << t.get_minutes() << ":"; if (t.get_seconds() < 10) if (t.get_seconds() < 10) cout << "0"; cout << t.get_seconds(); cout << "0"; cout << t.get_seconds();

} }

Since a procedure does not have a return value, it must have a Since a procedure does not have a return value, it must have a side effect. side effect.

Ideally, a procedure has only one side effect (simplicity…)Ideally, a procedure has only one side effect (simplicity…)

Page 22: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

2222

Example of Procedure (printtime.cpp)Example of Procedure (printtime.cpp) 01: 01: #include#include <iostream> <iostream> 02:  02: #include#include <iomanip> <iomanip>  04:  04: usingusing namespacenamespace std; std;  06:  06: #include#include "ccc_time.cpp" "ccc_time.cpp" 07:  07:  08:  08: /**/** 09:  09:    Print a time in the format h:mm:ss   Print a time in the format h:mm:ss 10:  10:    @param t the time to print   @param t the time to print 11:  11: */*/ 12: void  12: void print_timeprint_time(Time t) {  (Time t) {   14:    cout << t. 14:    cout << t.get_hoursget_hours() << ":";() << ":"; 15:     15:    ifif (t. (t.get_minutesget_minutes() < 10) cout << "0";() < 10) cout << "0"; 16:    cout << t. 16:    cout << t.get_minutesget_minutes() << ":";() << ":"; 17:     17:    ifif (t. (t.get_secondsget_seconds() < 10) cout << "0";() < 10) cout << "0"; 18:    cout << t. 18:    cout << t.get_secondsget_seconds();(); 19: } 19: } 21: int  21: int mainmain(){  (){   23:    Time  23:    Time liftoffliftoff(7, 0, 15);(7, 0, 15); 24:    Time now; 24:    Time now; 25:    cout << "Liftoff: "; 25:    cout << "Liftoff: "; 26:     26:    print_timeprint_time(liftoff); (liftoff); 27:    cout << "\n";27:    cout << "\n"; 28:  28:  29:    cout << "Now: "; 29:    cout << "Now: "; 30:     30:    print_timeprint_time(now);(now); 31:    cout << "\n"; 31:    cout << "\n"; 32:  32:  33:     33:    returnreturn 0; 0; 34: } 34: }   

Page 23: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

2323

Reference Parameters Reference Parameters The parameter variables we have looked at The parameter variables we have looked at

so far are called so far are called value parametersvalue parameters. . Value parameters are separate variables Value parameters are separate variables

from the ones in main() (or another calling from the ones in main() (or another calling function). function).

Modification of value parameters does not Modification of value parameters does not affect the original value. affect the original value.

A A reference parameterreference parameter does not create a new does not create a new variable, but refer to an existing variable. variable, but refer to an existing variable.

Any change in a reference parameter is Any change in a reference parameter is actually a change in the variable to which it actually a change in the variable to which it refers. refers.

Reference parameters are indicated using an Reference parameters are indicated using an & between the parameter's type and name. & between the parameter's type and name.

Page 24: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

2424

Reference Parameters (example)Reference Parameters (example) Example:Example: /**/** Raises the salary of employee by the Raises the salary of employee by the percentage being specified. percentage being specified.

@param e employee affected (whose salary is raised)@param e employee affected (whose salary is raised) @param by percentage to be raised@param by percentage to be raised **/**/ void raise_salary(Employee& e, double by) {void raise_salary(Employee& e, double by) {

        double new_salary; double new_salary; new_salary = e.get_salary() * ( 1 + by / 100);new_salary = e.get_salary() * ( 1 + by / 100); e.set_salary(new_salary);e.set_salary(new_salary); } }

Page 25: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

2525

Reference Parameters (cont.)Reference Parameters (cont.) General syntax: General syntax:

<type_name>& <par_name><type_name>& <par_name> ExampleExample

Employee& eEmployee& eint& resultint& result

Purpose:Purpose:

Define a parameter that is bound to a Define a parameter that is bound to a variable in the function call, to allow variable in the function call, to allow the function to modify that variable. the function to modify that variable.

Page 26: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

2626

Example using Example using raise_salary(..)raise_salary(..)

/* This program raises the salary of employee “Harry /* This program raises the salary of employee “Harry Hacker” by 5% and Hacker” by 5% and prints the final salary…prints the final salary…

*/ */ ……. Other stuff... . Other stuff... ……. Including function declaration or definition…. Including function declaration or definition…

int int mainmain() {  () {  Employee Employee harryharry("Hacker, Harry", 45000.00);("Hacker, Harry", 45000.00);raise_salaryraise_salary(harry, 5);(harry, 5);cout << "New salary: " cout << "New salary: "

<< harry.<< harry.get_salaryget_salary() << "\n";() << "\n";returnreturn 0; 0;

}}   

Page 27: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

2727

Constant Reference Parameters Constant Reference Parameters

General syntax: General syntax: const <const <type>type>&& <par_name> <par_name>

Example:Example: const int& valconst int& val

Purpose:Purpose: Define a parameter that is bound to a Define a parameter that is bound to a variable in the function call, to avoid the variable in the function call, to avoid the cost of copying the variable into the cost of copying the variable into the parameter variable without the risk of parameter variable without the risk of altering the variable whose value is used. altering the variable whose value is used.

Page 28: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

2828

Reference Parameters (cont.)Reference Parameters (cont.) Reference parameters are Reference parameters are more efficientmore efficient

than value parameters because they do not than value parameters because they do not make copies of the parameters. make copies of the parameters.

Passing variables by Passing variables by constant referenceconstant reference improves performance, but prevents the improves performance, but prevents the function from changing the value of the function from changing the value of the parameter. parameter.

Objects make good constant reference Objects make good constant reference parameters because they tend to have parameters because they tend to have several attributes that need to be copied. several attributes that need to be copied. Passing numbers by constant reference is Passing numbers by constant reference is generally not worth the effort. generally not worth the effort.

Page 29: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

2929

Activation Record of Function CallActivation Record of Function Call For each execution of a function a data structure For each execution of a function a data structure

called the called the activation record of the current activation record of the current callcall is created. is created.

Activation RecordActivation Record:: • Data structure (memory space) that contains area to Data structure (memory space) that contains area to

store (at least): store (at least): Each of the Each of the local variableslocal variables (parameters and variables (parameters and variables

declared inside the function)declared inside the function) Return address of the current function callReturn address of the current function call

• Depends on the particular functionDepends on the particular function• New instance is created whenever the function is called New instance is created whenever the function is called

and is destroyed when that execution ends.and is destroyed when that execution ends.• Stored as part of the Stored as part of the process stack process stack assigned to the assigned to the

execution of the program by the operating system.execution of the program by the operating system.

Page 30: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

3030

Variable ScopeVariable Scope A program can have variables with the A program can have variables with the

same name in different functions. same name in different functions.

The part within a program in which a The part within a program in which a variable is visible is known as the variable is visible is known as the scopescope of the variableof the variable. .

The scope of a variable extends from its The scope of a variable extends from its definition to the end of the block in which definition to the end of the block in which it was defined. it was defined.

Page 31: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

3131

Example of Variable ScopeExample of Variable Scopedouble future_value(double initial_balance, double future_value(double initial_balance, double p, int n) {double p, int n) {

    double r = intial_balance * pow(1 + p / 100, n);    double r = intial_balance * pow(1 + p / 100, n);    return r;    return r;

}}  

int main() {int main() { cout << "Please enter the interest rate in percent: "; cout << "Please enter the interest rate in percent: "; double r; double r; cin >> r; cin >> r;   double balance = future_value(10000, r, 10); double balance = future_value(10000, r, 10); cout << "After 10 years the balance is"  cout << "After 10 years the balance is"

<< balance<< balance      << "\n";      << "\n";   return 0; return 0;

} }

Page 32: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

3232

Global VariablesGlobal Variables Global variablesGlobal variables are variables that are variables that

are defined outside functions. are defined outside functions.

A global variable is visible to all A global variable is visible to all functions that are defined after it. functions that are defined after it.

Sometimes global variables cannot Sometimes global variables cannot be avoided (cin, cout, and cwin), but be avoided (cin, cout, and cwin), but you should make every effort to you should make every effort to avoid global variables in your avoid global variables in your program. program.

Page 33: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

3333

Example of Global VariablesExample of Global Variables 01: 01: #include#include <iostream> <iostream>  02: 02: #include#include <cmath> <cmath>  03: 03:   04: 04: usingusing namespacenamespace std; std;  05: 05:   06: double balance;06: double balance;  07: 07:   08: 08: /** /**   09: 09:    Accumulates interest in the global variable balance   Accumulates interest in the global variable balance  10: 10:    @param p the interest rate in percent   @param p the interest rate in percent  11: 11:    @param n the number of periods the investment is held   @param n the number of periods the investment is held  12: 12: */*/  13: void 13: void future_valuefuture_value(int p, int n) {  (int p, int n) {    15:    balance = balance * 15:    balance = balance * powpow(1 + p / 100, n); (1 + p / 100, n);   16: }16: }  17: 17:   18: int 18: int mainmain() {  () {    20:    balance = 10000;20:    balance = 10000;  21:    21:    future_valuefuture_value(5, 10);(5, 10);  22:    cout << "After ten years, the balance is “22:    cout << "After ten years, the balance is “  23:       << balance << "\n";23:       << balance << "\n";  24:    24:    returnreturn 0; 0;  25: } 25: }

Page 34: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

3434

Stepwise RefinementStepwise Refinement One of the most powerful strategies for problem One of the most powerful strategies for problem

solving is the process of solving is the process of stepwise refinementstepwise refinement. . To solve a difficult task, break it down into To solve a difficult task, break it down into

simpler tasks; then keep breaking down the simpler tasks; then keep breaking down the simpler tasks into even simpler ones, until you simpler tasks into even simpler ones, until you are left with tasks that you know how to solve. are left with tasks that you know how to solve.

How do you get coffee? How do you get coffee? • Ask someone else to do it. Ask someone else to do it. • Make coffee. Make coffee.

OK, how do you make coffee? OK, how do you make coffee? • Make instant coffee. Make instant coffee. • Brew Coffee. Brew Coffee.

How do you make instant coffee? How do you make instant coffee? • Start by boiling water. Start by boiling water. • Etc. Etc.

Page 35: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

3535

From Pseudocode to CodeFrom Pseudocode to Code

Before starting to program, we need to have a plan. Before starting to program, we need to have a plan.

Any time you need something more than once, it's a good Any time you need something more than once, it's a good idea to turn that into a function.. idea to turn that into a function..

Rather than writing the entire function, begin by writing the Rather than writing the entire function, begin by writing the comments. comments.

Example:Example: Writing the function to convert int to string… Writing the function to convert int to string…

/** Turns a number into its English name. /** Turns a number into its English name. @param n a positive integer < 1,000,000 @param n a positive integer < 1,000,000 @return the name of n (e.g. "two hundred @return the name of n (e.g. "two hundred seventy seventy four" four" */ */ string int_name(int n);string int_name(int n);

Page 36: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

3636

From Pseudocode to Code (cont.)From Pseudocode to Code (cont.) /**/**

    Turns a digit into its English name    Turns a digit into its English name    @param n an integer between 1 and 9    @param n an integer between 1 and 9    @return the name of n ("one" ... "nine")    @return the name of n ("one" ... "nine") */ */ string digit_name(int n); string digit_name(int n);   /** /**    Turns a number between 10 and 19 into its English     Turns a number between 10 and 19 into its English name.name.    @param n an integer between 10 and 19    @param n an integer between 10 and 19    @return the name of n ("ten"..."nineteen")    @return the name of n ("ten"..."nineteen") */ */ string teen_name(int n); string teen_name(int n);   /** /**    Gives the English name of a multiple of 10    Gives the English name of a multiple of 10    @param n an integer between 2 and 9    @param n an integer between 2 and 9    @return the name of 10 * n ("twenty"..."ninety")    @return the name of 10 * n ("twenty"..."ninety") */ */ string tens_name(int n); string tens_name(int n);

Page 37: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

3737

From Pseudocode to Code (cont.)From Pseudocode to Code (cont.)

What is missing? What is missing? • For hundreds, we show the digit name For hundreds, we show the digit name

then write "hundreds". then write "hundreds". • For 100 - 999, we can put calls to For 100 - 999, we can put calls to

functions above together to write functions above together to write number. number.

• For numbers over 1,000, we call For numbers over 1,000, we call functions above to write the number of functions above to write the number of thousands, print "thousands", then call thousands, print "thousands", then call the above functions again to write the the above functions again to write the rest of the number. rest of the number.

Page 38: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

3838

From Pseudocode to Code (cont.)From Pseudocode to Code (cont.) When algorithms are complicated, we first write them as When algorithms are complicated, we first write them as

pseudocodepseudocode. . Pseudocode is somewhere between C++ and English.Pseudocode is somewhere between C++ and English. string string

int_name(int n)int_name(int n)

  string int_name(int n)string int_name(int n) {{   int c = n; // the part that needs to be converted    int c = n; // the part that needs to be converted    string r; // the return value     string r; // the return value     if (c >= 1000) {   if (c >= 1000) {       r =        r = name of thousands inname of thousands in c + "thousand" c + "thousand"              remove thousands fromremove thousands from c c   }   }     if (c >= 100) {   if (c >= 100) {       r = r +        r = r + name of hundreds inname of hundreds in c + "hundreds" c + "hundreds"              remove hundreds fromremove hundreds from c c   }   }     if (c >= 20) {   if (c >= 20) {       r = r +        r = r + name of tens inname of tens in c c              remove tens fromremove tens from c c   }   }     if (c >= 10) {   if (c >= 10) {       r = r +        r = r + name ofname of c c       c = 0       c = 0   }   }     if (c > 0)   if (c > 0)       r = r +        r = r + name ofname of c; c;     return r;   return r; } }

Page 39: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

3939

From Pseudocode to Code (cont.)From Pseudocode to Code (cont.) Assume that the following functions are implemented (they exist)Assume that the following functions are implemented (they exist)

/**/**    Turns a digit into its English name    Turns a digit into its English name    @param n an integer between 1 and 9    @param n an integer between 1 and 9    @return the name of n ("one" ... "nine")    @return the name of n ("one" ... "nine") */ */ string digit_name(int n); string digit_name(int n);   /** /**    Turns a number between 10 and 19 into its     Turns a number between 10 and 19 into its

English name.English name.    @param n an integer between 10 and 19    @param n an integer between 10 and 19    @return the name of n ("ten"..."nineteen")    @return the name of n ("ten"..."nineteen") */ */ string teen_name(int n); string teen_name(int n);   /** /**    Gives the English name of a multiple of 10    Gives the English name of a multiple of 10    @param n an integer between 2 and 9    @param n an integer between 2 and 9    @return the name of 10 * n ("twenty"..."ninety")    @return the name of 10 * n ("twenty"..."ninety") */ */ string tens_name(int n); string tens_name(int n);

Page 40: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

4040

From Pseudocode to Code (cont.)From Pseudocode to Code (cont.) 063: 063: /**/** 064:  064:    Turn a number into its English name   Turn a number into its English name 065:  065:    @param n a positive integer < 1,000,000   @param n a positive integer < 1,000,000 066:  066:    @return the name of n (e.g. "two hundred seventy four")   @return the name of n (e.g. "two hundred seventy four") 067:  067: */*/ 068: string  068: string int_nameint_name(int n) {(int n) { 069: int c = n;  069: int c = n; /* the part that still needs to be converted *//* the part that still needs to be converted */ 070:    string r;  070:    string r; /* the return value *//* the return value */ 071:  071:  072:     072:    ifif (c >= 1000) {  (c >= 1000) {   074:       r =  074:       r = int_nameint_name(c / 1000) + " thousand"; // recursive call…(c / 1000) + " thousand"; // recursive call… 075:       c = c % 1000; 075:       c = c % 1000; 076:    } 076:    } 077:  077:  078:     078:    ifif (c >= 100) {  (c >= 100) {   080:       r = r + " " +  080:       r = r + " " + digit_namedigit_name(c / 100) + " hundred";(c / 100) + " hundred"; 081:       c = c % 100; 081:       c = c % 100; 082:    } 082:    } 083:  083:  084:     084:    ifif (c >= 20) {  (c >= 20) {   086:       r = r + " " +  086:       r = r + " " + tens_nametens_name(c / 10);(c / 10); 087:       c = c % 10; 087:       c = c % 10; 088:    } 088:    } 089:     089:     090:     090:    ifif (c >= 10) {  (c >= 10) {   092:       r = r + " " +  092:       r = r + " " + teen_nameteen_name(c);(c); 093:       c = 0; 093:       c = 0; 094:    } 094:    } 095:  095:  096:     096:    ifif (c > 0) (c > 0) 097:       r = r + " " +  097:       r = r + " " + digit_namedigit_name(c);(c); 098:  098:  099:     099:    returnreturn r; r; 100: }  100: }

Page 41: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

4141

From Pseudocode to Code (cont.)From Pseudocode to Code (cont.) Implementation of function digit_name(…)Implementation of function digit_name(…)

006: 006: /**/** 007:  007:    Turn a digit into its English name   Turn a digit into its English name 008:  008:    @param n an integer between 1 and 9   @param n an integer between 1 and 9 009:  009:    @return the name of n ("one" . . . "nine")   @return the name of n ("one" . . . "nine") 010:  010: */*/ 011: string  011: string digit_namedigit_name(int n)(int n) 012: {   012: {   013:     013:    ifif (n == 1) (n == 1) returnreturn "one"; "one"; 014:     014:    ifif (n == 2) (n == 2) returnreturn "two"; "two"; 015:     015:    ifif (n == 3) (n == 3) returnreturn "three"; "three"; 016:     016:    ifif (n == 4) (n == 4) returnreturn "four"; "four"; 017:     017:    ifif (n == 5) (n == 5) returnreturn "five"; "five"; 018:     018:    ifif (n == 6) (n == 6) returnreturn "six"; "six"; 019:     019:    ifif (n == 7) (n == 7) returnreturn "seven"; "seven"; 020:     020:    ifif (n == 8) (n == 8) returnreturn "eight"; "eight"; 021:     021:    ifif (n == 9) (n == 9) returnreturn "nine"; "nine"; 022:     022:    returnreturn ""; ""; 023: } 023: } 024:  024:

Page 42: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

4242

From Pseudocode to Code (cont.)From Pseudocode to Code (cont.) Function teen_name(…)Function teen_name(…)

025: 025: /**/** 026:  026:    Turn a number between 10 and 19 into its    Turn a number between 10 and 19 into its

English nameEnglish name 027:  027:    @param n an integer between 10 and 19   @param n an integer between 10 and 19 028:  028:    @return the name of n ("ten" . . . "nineteen")   @return the name of n ("ten" . . . "nineteen") 029:  029: */*/ 030: string  030: string teen_nameteen_name(int n)(int n) 031: {   031: {   032:     032:    ifif (n == 10) (n == 10) returnreturn "ten"; "ten"; 033:     033:    ifif (n == 11) (n == 11) returnreturn "eleven"; "eleven"; 034:     034:    ifif (n == 12) (n == 12) returnreturn "twelve"; "twelve"; 035:     035:    ifif (n == 13) (n == 13) returnreturn "thirteen"; "thirteen"; 036:     036:    ifif (n == 14) (n == 14) returnreturn "fourteen"; "fourteen"; 037:     037:    ifif (n == 15) (n == 15) returnreturn "fifteen"; "fifteen"; 038:     038:    ifif (n == 16) (n == 16) returnreturn "sixteen"; "sixteen"; 039:     039:    ifif (n == 17) (n == 17) returnreturn "seventeen"; "seventeen"; 040:     040:    ifif (n == 18) (n == 18) returnreturn "eighteen"; "eighteen"; 041:     041:    ifif (n == 19) (n == 19) returnreturn "nineteen"; "nineteen"; 042:     042:    returnreturn ""; ""; 043: } 043: } 044:  044:    

Page 43: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

4343

From Pseudocode to Code (cont.)From Pseudocode to Code (cont.) Function tens_name(…)Function tens_name(…)

045: 045: /**/** 046:  046:    Give the English name of a multiple of 10   Give the English name of a multiple of 10 047:  047:    @param n an integer between 2 and 9   @param n an integer between 2 and 9 048:  048:    @return the name of 10 * n ("twenty" . . .    @return the name of 10 * n ("twenty" . . . "ninety")"ninety") 049:  049: */*/ 050: string  050: string tens_nametens_name(int n)(int n) 051: {   051: {   052:     052:    ifif (n == 2) (n == 2) returnreturn "twenty"; "twenty"; 053:     053:    ifif (n == 3) (n == 3) returnreturn "thirty"; "thirty"; 054:     054:    ifif (n == 4) (n == 4) returnreturn "forty"; "forty"; 055:     055:    ifif (n == 5) (n == 5) returnreturn "fifty"; "fifty"; 056:     056:    ifif (n == 6) (n == 6) returnreturn "sixty"; "sixty"; 057:     057:    ifif (n == 7) (n == 7) returnreturn "seventy"; "seventy"; 058:     058:    ifif (n == 8) (n == 8) returnreturn "eighty"; "eighty"; 059:     059:    ifif (n == 9) (n == 9) returnreturn "ninety"; "ninety"; 060:     060:    returnreturn ""; ""; 061: } 061: } 062:  062:   

Page 44: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

4444

From Pseudocode to Code (cont.)From Pseudocode to Code (cont.) Pseudocode can be easier to understand than a verbal Pseudocode can be easier to understand than a verbal

description. description.

It's best not to muddy the pseudocode with minor details. It's best not to muddy the pseudocode with minor details.

The pseudocode did not take into account spaces between The pseudocode did not take into account spaces between the words. the words.

Note that the helper functions needed to be declared Note that the helper functions needed to be declared before the int_name function. before the int_name function.

The int_name function calls itself (called The int_name function calls itself (called recursionrecursion): ): if (c >= 1000) { if (c >= 1000) { r = int_name(c / 1000) + " thousand"; r = int_name(c / 1000) + " thousand"; c = c % 1000; c = c % 1000; }}

Page 45: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

4545

WalkthroughsWalkthroughs Before entrusting a subprogram to a Before entrusting a subprogram to a

computer, it is a good idea to put it through computer, it is a good idea to put it through a dry run or a dry run or walkthourghwalkthourgh. .

Take out an index card and write down the Take out an index card and write down the name of the function you want to study. name of the function you want to study.

Write down the names of the function Write down the names of the function variables in a table, since you will update variables in a table, since you will update them as you walk through the code. them as you walk through the code.

See examples …See examples …

Page 46: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

4646

PreconditionsPreconditions What should a function do when called with an What should a function do when called with an

inappropriate value (e.g. sqrt(-1))? inappropriate value (e.g. sqrt(-1))? • A function can fail safely. For example, the digit_name function A function can fail safely. For example, the digit_name function

simply returns an empty string when it is called with an simply returns an empty string when it is called with an unexpected value. unexpected value.

• A function can terminate. Many functions in the cmath library A function can terminate. Many functions in the cmath library will terminate if given an illegal value. will terminate if given an illegal value.

The most brutal method is to print a message and The most brutal method is to print a message and terminate the entire program. terminate the entire program.

C++ has a very sophisticated mechanism called an C++ has a very sophisticated mechanism called an exceptionexception. .

Whenever possible, it is desirable to avoid termination of Whenever possible, it is desirable to avoid termination of the program (although that is hard). the program (although that is hard).

We will discuss using assert(). We will discuss using assert().

Page 47: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

4747

AssertionsAssertions General syntax of assert statement: General syntax of assert statement: assert(assert(expressionexpression););

Example:Example: assert(x >= 0);assert(x >= 0);

Purpose:Purpose: If the expression is true, do nothing. If the expression is true, do nothing. If the expression is false, terminate If the expression is false, terminate the program, displaying the file name,the program, displaying the file name,line number, and expression.line number, and expression.

Page 48: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

4848

Preconditions and PostconditionsPreconditions and Postconditions

Precondition Precondition of a function: of a function: • condition that must be true when the condition that must be true when the

execution of the function begins in order execution of the function begins in order for it to work correctlyfor it to work correctly

• if not true, the function may work if not true, the function may work incorrectlyincorrectly

PostconditionPostcondition of a function: of a function: • condition that will be true when the condition that will be true when the

execution of the function ends, provided execution of the function ends, provided that the precondition is satisfiedthat the precondition is satisfied

Page 49: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

4949

Assertions (cont.)Assertions (cont.)

To use assert() you must use directive: To use assert() you must use directive: #include <cassert>#include <cassert>

assert()assert() is really a is really a macromacro - a special instruction to the - a special instruction to the compiler that inserts complex code into the program. compiler that inserts complex code into the program.

Example:Example: double future_value(double initialBalance, double future_value(double initialBalance,

double p, int n) {double p, int n) {  assert(p >= 0);  assert(p >= 0);  assert(n >= 0);  assert(n >= 0);    return initialBalance * pow(1+p/100, n);  return initialBalance * pow(1+p/100, n);

} }

Page 50: 1 Chapter 5: Functions  Chapter Goals To be able to program functions and proceduresTo be able to program functions and procedures To become familiar

5050

Preconditions (cont.)Preconditions (cont.) As a programmer, you must fully document any As a programmer, you must fully document any

preconditionspreconditions that the function must meet. That that the function must meet. That is, the legal values for function inputis, the legal values for function input. .

Example:Example: /**/**  Computes the value of an investment with compound interest.  Computes the value of an investment with compound interest.  @param initial_balance the initial value of the investment  @param initial_balance the initial value of the investment  @param p the interest rate in percent; must be >= 0  @param p the interest rate in percent; must be >= 0  @param n the number of periods the investment is held;   @param n the number of periods the investment is held;

must be >= 0must be >= 0

  @return  @return the balance after n periodsthe balance after n periods */  */