1 functions chapter 7 2 hope you can function! what is r2d2 doing here? what is his function? who is...
TRANSCRIPT
1
FunctionsFunctionsChapter 7
2
Hope Hope youyou can function! can function!
What is R2D2 doing here?
What is his function?
Who is Nibble?
Can he function?
IS he a function?
Who is this nut?
3Top-Down Structured DesignTop-Down Structured Designwith Void Functionswith Void Functions Recall two types of functions Value returning function
– computes a single value– returns value to calling code– uses return command
Void function (procedure)– called as a statement– executes some task
This chapter focuses on the void function
4
When to Use FunctionsWhen to Use Functions
To help make the program more understandable
To modularize the tasks of the program– building blocks of the program
Write a module once– those lines of source code are called multiple
times in the program
5
Need for FunctionsNeed for Functions
Functions perform a task.Functions perform a task.
6
Writing Void FunctionsWriting Void Functions
Declare functions (their names and parameters)– list before main( )– called prototypes
void print_summary (float total);void calculate_rates ( );void find_matching_records (char id[]);
void main ( ) { . . .
void print_summary (float total);void calculate_rates ( );void find_matching_records (char id[]);
void main ( ) { . . .
Function Name Parameter list
Note, must includesemicolon ;
Note, must includesemicolon ;
7
Writing Void FunctionsWriting Void Functions
Define functions below main( )– specify source code– include heading again
void main ( ) { . . . print_summary (rpt_total); . . . } void print_summary (int total) { . . . cout << . . . }
void main ( ) { . . . print_summary (rpt_total); . . . } void print_summary (int total) { . . . cout << . . . }
Note no semicolon with
definition
Note no semicolon with
definition
8
Flow of ControlFlow of Control
First statement executed in any program is the first statement in the function main( )
When another function called– logical control passed to first statement in that
function’s body– program proceeds through sequence of statements
within the function When last statement of function executed
– control returns to where function was called– control given to next command after the call
9
Flow of ControlFlow of Control
void main ( ) { . . . print_summary (rpt_total); revenue = rpt_total * .72675; . . . } void print_summary (int total) { . . . cout << . . . }
void main ( ) { . . . print_summary (rpt_total); revenue = rpt_total * .72675; . . . } void print_summary (int total) { . . . cout << . . . }
- first statement of main- function call, jumps to first statement of that function- proceeds through function- returns to next statement after call
- first statement of main- function call, jumps to first statement of that function- proceeds through function- returns to next statement after call
10
Improving FunctionsImproving Functions
We need to communicate to the functions
We need to communicate to the functions
11
Improving FunctionsImproving Functions
Sending values to the functionswith value parameters.
Sending values to the functionswith value parameters.
12
Function ParametersFunction Parameters
Make functions more versatile Send to the function a value
– tells it how many times to do something– gives it a value to be used in some way (printed,
calculated, etc.)
13
Function ParametersFunction Parameters Formal parameter
– declared in the function heading Actual parameter
– variable or expression listed in a call (invocation) of the function
void main ( ) { . . . print_summary (rpt_total); . . . } void print_summary (int total) { . . . cout << . . . }
void main ( ) { . . . print_summary (rpt_total); . . . } void print_summary (int total) { . . . cout << . . . }
14
Function Call (Invocation)Function Call (Invocation)
Use the name of the function as if it is a statement
When the program reaches t hat statement, Control is then transferred to the function
void main ( ) { . . . print_summary (rpt_total); . . . } void print_summary (int total) { . . . cout << . . . }
void main ( ) { . . . print_summary (rpt_total); . . . } void print_summary (int total) { . . . cout << . . . }
15
Function DeclarationsFunction Declarations
Why the prototypes? All identifiers (including function names)
must be declared before they are used
Compiler must know about the function
void calculate_rates ( );void find_matching_records (char id[]);
void main ( ) { . . . calculate_rates ( ); find_matching_records (emp_id);
void calculate_rates ( );void find_matching_records (char id[]);
void main ( ) { . . . calculate_rates ( ); find_matching_records (emp_id);
ParametersParameters
Function nameFunction nameFunction typeFunction type
16
Function DeclarationsFunction Declarations
It is also legal to include the definition (body) of the function with the heading all before main( )
void print_summary (int total) { . . . cout << . . . } void main ( ) { . . . print_summary (rpt_total); revenue = rpt_total * .72675; . . . }
void print_summary (int total) { . . . cout << . . . } void main ( ) { . . . print_summary (rpt_total); revenue = rpt_total * .72675; . . . }
This takes care of informing thecompiler of what it needs
and defining the source code also
This takes care of informing thecompiler of what it needs
and defining the source code also
17
Syntax of the Parameter ListSyntax of the Parameter List
In parentheses For each parameter
– specify type then name– separate type-name pairs with commas
void print_max_value (int value_1, int value_2, int value_3) { . . . }
void print_max_value (int value_1, int value_2, int value_3) { . . . }
18
Local VariablesLocal Variables
A variable declared within a block It is not accessible outside of that block Memory allocated when statement reached
within the block Memory de-allocated when block finished
void print_max_value (int value_1, int value_2, int value_3) { int hold_value; hold_value = value_1; if (value_2 > hold_value)
hold_value = value_2; . . . }
void print_max_value (int value_1, int value_2, int value_3) { int hold_value; hold_value = value_1; if (value_2 > hold_value)
hold_value = value_2; . . . }
Block
19
Local VariablesLocal Variables What if local variable (in the block) has same
name as a variable outside the block? Inside the block
– the local variable takes precedence
– the exterior variable not accessible
Outside the block– the local variable
is not accessible
void print_sum (int n1, int n2) { int sum; sum = n1 + n2; cout << sum; }
void main( ){ float sum, x, y; . . . print_sum (x, 34); . . .
void print_sum (int n1, int n2) { int sum; sum = n1 + n2; cout << sum; }
void main( ){ float sum, x, y; . . . print_sum (x, 34); . . .
20
The Return StatementThe Return Statement A void function does not return a function
value Two ways to have the function return
control to calling routine– when the function finishes all statements– place the command return in the function
void print_odd_even (int x){
if (x % 2) // no remainder => even { cout << "even";
return; }cout << "odd";
}
void print_odd_even (int x){
if (x % 2) // no remainder => even { cout << "even";
return; }cout << "odd";
}
21
Naming Void FunctionsNaming Void Functions
Remember … void functions are used as statements
The name should suggest what task it is performing– implies use of a verb
It helps the program self document
void print_the_sum ( );void max_value (int a, int b, int c);void calculate_deductions (float hours);void cube_root (float num);
void print_the_sum ( );void max_value (int a, int b, int c);void calculate_deductions (float hours);void cube_root (float num); Which are
good names?Which are
good names?
22
Header FilesHeader Files
Recall our use of #include <xxxx.h> Header files contain ... named constants like
const int INT_MAX = 32767; new type definitions (besides int, char, etc.) function prototypes like
float pow( float, float );float sqrt( float );char toupper( char );
int islower( char );
23
Header FilesHeader Files
Note the help window from Turbo C++ concerning header files
We most often use
string.hiostream.hfstream.hiomanip.hmath.h
We most often use
string.hiostream.hfstream.hiomanip.hmath.h
24
Value ParametersValue Parameters
Defn => a formal parameter that receives a copy of the contents of the corresponding actual parameter
void main ( ) { . . . print_summary (rpt_total); . . . } void print_summary (int total) { . . . cout << . . . }
void main ( ) { . . . print_summary (rpt_total); . . . } void print_summary (int total) { . . . cout << . . . }
17
25
Value ParameterValue Parameter
Acts much like an assignment of a value to a variable
The formal parameter is considered local to the function
The actual parameter may be an expression or a constant
void main ( ) { print_summary (0.5*rpt_total); . . . print_summary (200); } void print_summary (int total) { . . . cout << . . . }
void main ( ) { print_summary (0.5*rpt_total); . . . print_summary (200); } void print_summary (int total) { . . . cout << . . . }
26
Value ParametersValue Parameters
Consider … When we change the contents of the value parameter in the function …– What (if anything) happens to the actual
parameter?
No, nothing happens.The actual parameter remains unchanged
No, nothing happens.The actual parameter remains unchanged
27
Reference ParametersReference Parameters
What if we wanted the actual parameter to change?
C++ allows us to do this with reference parameters.
What is different in thisversion of the function?What is different in thisversion of the function?
28
Reference ParametersReference Parameters
It would be helpful tobe able to have the functions
communicate back to thecalling module.
It would be helpful tobe able to have the functions
communicate back to thecalling module.
29
Reference ParametersReference Parameters
Reference Parameters providethat capability
Reference Parameters providethat capability
30
Reference ParametersReference Parameters
Use the ampersand & between the parameter type and the identifier
What actually happens is that this causes the address of the actual parameter to be sent to the formal parameter
Then anything that happens to the formal parameter is happening to the actual parameter
31Contrast Contrast Value & Reference ParametersValue & Reference Parameters
Receives copy of value Actual parameter can be
constant, variable, expression
Value travels one way only (in)
Exact match of types (formal & actual) not critical
Receives address of actual parameter
Actual parameter must be a variable
Value can be thought of as traveling both ways (in and out)
Formal & actual parameters must be of same type
ValueValue ReferenceReference
32
Reference ParametersReference Parameters
5 10
5
Recall our previous model for a function with value parameters(values go in only)
Now consider a new version for reference parametersValues go bothin & out
33
Another Look at Value Another Look at Value ParametersParameters
CALLINGBLOCK
FUNCTION CALLED
“incoming”
value ofactual parameter
Sometimes called“Pass-by-value”
34
Another Look at Reference Another Look at Reference ParametersParameters
CALLINGBLOCK FUNCTION
CALLED
“incoming”
original value ofactual parameter
“outgoing”
changed value ofactual parameter OR,Sometimes called
“Pass by reference”Sometimes called
“Pass by reference”
35
Another Version ofAnother Version ofPass-by-referencePass-by-reference
CALLINGBLOCK FUNCTION
CALLED
actual parameter has no value yet when call occurs
“outgoing”
new value ofactual parameter
36Matching Actual & Formal Matching Actual & Formal ParametersParameters Must be same number of parameters in call
as in declaration/definition Parameters are paired off left to right as they
occur void print_max (int n1, int n2, int n3) { if ( … … cout << … }
int main(){ … print_max (x, 17, y + z); …
void print_max (int n1, int n2, int n3) { if ( … … cout << … }
int main(){ … print_max (x, 17, y + z); …
37
Actual & Formal ParametersActual & Formal Parameters
Actual (in the call) value parameters may be variables, constants, or expressions
void print_max (int n1, int n2, int n3) { if ( … … cout << … }
int main(){ … print_max (x, 17, y + z); …
void print_max (int n1, int n2, int n3) { if ( … … cout << … }
int main(){ … print_max (x, 17, y + z); …
38
Actual & Formal ParametersActual & Formal Parameters
Actual (in the call) reference parameters must be variables
void swap (int &n1, int &n2) { int hold = n1; n1 = n2; n2 = hold}
int main(){ int x = 5; y = 3; z = 12 swap (x, z); swap (z, y); …
void swap (int &n1, int &n2) { int hold = n1; n1 = n2; n2 = hold}
int main(){ int x = 5; y = 3; z = 12 swap (x, z); swap (z, y); …
What ends up stored where?
Or … who’s on first?
What ends up stored where?
Or … who’s on first?
x = y = z = x = y = z =
39
Reusing FunctionsReusing Functions
A programmer can use reuse functions– from other programs you have written– utility functions from other sources
Such functions can be considered “black boxes”– you merely call the function– you need not know how it does what it does– this is called “encapsulation”
40
Reusing FunctionsReusing Functions
To call a function a programmer must know the interface– the name of the function
– the names and types of the parameters
– any pre- or post-conditions Pre-conditions -- any requirements of the function
– max or min values of parameters
– a certain file must be open, etc. Post-conditions -- guaranteed results if pre-
conditions met
41
The Assertion StatementThe Assertion Statement A command that declares a certain condition
– if the condition is not met, the program is halted with an error message
Helps programmer catch pre-conditions or other program module requirements
The assertions can also help comment or document the program
Note #include <assert.h>Note #include <assert.h>
42
Preconditions and PostconditionsPreconditions and Postconditions
The precondition is an assertion describing everything that the function requires to be true at the moment the function is invoked.
The postcondition describes the state at the moment the function finishes executing.
The caller is responsible for ensuring the precondition, and the function code must ensure the postcondition.
FOR EXAMPLE . . .
43
Function with PostconditionsFunction with Postconditionsvoid GetRating ( /* out */ char& Letter)// Precondition: None// Postcondition:User has been prompted to enter a char// && Letter == one of these input values: E,G,A, or P{ cout << “Enter employee rating.” << endl;
cout << “Use E, G, A, or P : ” ; do { cin >> Letter; if ( (Letter != ‘E’) && (Letter != ‘G’)
&& (Letter != ‘A’) && (Letter != ‘P’) )
cout << “Rating invalid. Enter again: ”; } while ( (Letter != ‘E’) && (Letter != ‘G’)
&& (Letter != ‘A’) && (Letter != ‘P’) );}
void GetRating ( /* out */ char& Letter)// Precondition: None// Postcondition:User has been prompted to enter a char// && Letter == one of these input values: E,G,A, or P{ cout << “Enter employee rating.” << endl;
cout << “Use E, G, A, or P : ” ; do { cin >> Letter; if ( (Letter != ‘E’) && (Letter != ‘G’)
&& (Letter != ‘A’) && (Letter != ‘P’) )
cout << “Rating invalid. Enter again: ”; } while ( (Letter != ‘E’) && (Letter != ‘G’)
&& (Letter != ‘A’) && (Letter != ‘P’) );}
States function’s guaranteeStates function’s guarantee
44
Function with Preconditions Function with Preconditions and Postconditionsand Postconditions
void GetRoots( /* in */ float a, /* in */ float b, /* in */ float c, /* out */ float& Root1, /* out */ float& Root2 )
// Precondition: a, b, and c are assigned// && a != 0 && b*b - 4*a*c != 0// Postcondition: Root1 and Root2 are assigned && Root1 and Root2 // are roots of quadratic with coefficients a, b, c{
float temp;
temp = b * b - 4.0 * a * c;
Root1 = (-b + sqrt(temp) ) / ( 2.0 * a );
Root2 = (-b - sqrt(temp) ) / ( 2.0 * a );
return;}
void GetRoots( /* in */ float a, /* in */ float b, /* in */ float c, /* out */ float& Root1, /* out */ float& Root2 )
// Precondition: a, b, and c are assigned// && a != 0 && b*b - 4*a*c != 0// Postcondition: Root1 and Root2 are assigned && Root1 and Root2 // are roots of quadratic with coefficients a, b, c{
float temp;
temp = b * b - 4.0 * a * c;
Root1 = (-b + sqrt(temp) ) / ( 2.0 * a );
Root2 = (-b - sqrt(temp) ) / ( 2.0 * a );
return;} If preconditions are met,
postconditions areguaranteed
If preconditions are met,postconditions are
guaranteed
Why needed?Why needed?
45
Documenting Data Flow DirectionDocumenting Data Flow Direction
Data Flow <=> flow of information ...– from the call of the function – into the function– then from the function (if it is a reference
parameter)– back to where it is called
Specify in a comment in the parameter list
void GetRoots( /* in */ float a, /* in */ float b, /* in */ float c, /* out */ float& Root1, /* out */ float& Root2 )
void GetRoots( /* in */ float a, /* in */ float b, /* in */ float c, /* out */ float& Root1, /* out */ float& Root2 )
46
Testing and Debugging HintsTesting and Debugging Hints
Note documentation guidelines, Appendix E (pg A10-A13)
Make sure to have function prototypes near top of program
Use semicolon after prototype, but not after definition
Formal parameter list must specify type for each parameter
Use value parameters unless value must be returned to actual parameter
47
Testing and Debugging HintsTesting and Debugging Hints
Reference parameters must have & with the data type
Match sequence of actual parameter list to formal parameter list
Reference parameters must have variables in the call
Remember to use ... – debugger– variable watch window