9781423902225_IM_ch07

advertisement
C++ Programming: Program Design Including Data Structures, Fourth Edition
Chapter 7
User-Defined Functions II
At a Glance
Instructor’s Manual Table of Contents

Overview

Objectives

Teaching Tips

Quick Quizzes

Class Discussion Topics

Additional Projects

Additional Resources

Key Terms
7-1
C++ Programming: Program Design Including Data Structures, Fourth Edition
7-2
Lecture Notes
Overview
In Chapter 7, students learn how to use void functions. They will also examine reference
parameters and learn how to use them in a program. The scope of identifiers will be
examined in depth, as well as the purpose and use of static variables. Finally, students
will be introduced to the concept of function overloading.
Objectives
In this chapter, the student will:
 Learn how to construct and use void functions in a program
 Discover the difference between value and reference parameters
 Explore reference parameters and value-returning functions
 Learn about the scope of an identifier
 Examine the difference between local and global identifiers
 Discover static variables
 Learn function overloading
 Explore functions with default parameters
Teaching Tips
Void Functions
1. Explain the similarities and differences between void and value-returning functions.
Note that void and value-returning functions have similar structures; however, a void
function does not have a data type.
2. Point out that although void functions do not return a value, they can have a return
statement in order to exit the function.
Teaching
Tip
This chapter moves rapidly through some fairly complex concepts regarding
parameter passing. Make sure that students do not feel lost by asking questions
periodically as you work through the chapter. Start by verifying that students
understand why a call to a void function is a stand-alone statement.
Void Functions without Parameters
1. Discuss the general syntax for a void function without parameters. Also note the syntax
for calling a void function without parameters.
C++ Programming: Program Design Including Data Structures, Fourth Edition
7-3
2. Explain how void functions are typically used in programs, for example, for
input/output. Use Example 7-1 to illustrate.
Teaching
Tip
Note that although void functions do not return a value and may not even have
parameters, they are still useful in organizing a program so that it is more
modular. This creates cleaner code that is easier to follow, thus making later
modifications easier.
Void Functions with Parameters
1. Discuss the general syntax for a void function with parameters. Also note the syntax for
calling a void function with parameters.
2. Define the terms value parameter and reference parameter. Introduce the syntax for
using reference parameters using Example 7-3.
3. Step through Example 7-4 to illustrate the use of a void function with parameters.
Teaching
Tip
Although reference parameters will be discussed at length later in this chapter,
verify that students understand the basic concept of a reference parameter. Using
C++ reference parameters is tricky for beginning programmers; most students
will need some additional time to process this information.
Quick Quiz 1
1. What is the syntax of a void function header?
Answer: void functionName(formal parameter list)
2. What is the syntax of a void function call?
Answer: functionName(actual parameter list);
3. True or False: No information can be passed in and out of void functions without
parameters.
Answer: True
4. What is a reference parameter?
Answer: A formal parameter that receives the location (or memory address) of the
corresponding actual parameter
C++ Programming: Program Design Including Data Structures, Fourth Edition
7-4
Value Parameters
1. Discuss how a function call operates in terms of how the values in the actual parameters
are transferred to the formal parameters. Use Example 7-5 to illustrate this process.
Teaching
Tip
Emphasize that formal parameters retain their own copy of the value that is
passed from the actual parameter. This is a difficult concept to grasp, so you may
want to describe the process by drawing a simple diagram in addition to the ones
that are provided with the programs in this chapter. Reiterate that value
parameters work in a one-way direction, meaning that information from the
formal parameter cannot be passed back to the calling program, or actual
parameter.
Reference Variables as Parameters
1. Explain that reference parameters can change the value of the actual parameter because
the memory location of the value is passed, not the value itself.
2. Discuss the situations in which using reference parameters are useful.
Calculate Grade
1. Step through the Calculate Grade program (Example 7-6) to illustrate the use of
reference parameters.
2. Note that the & operator is used to signify a reference parameter. Use Figures 7-1
through 7-4 to guide students through the details of passing reference parameters.
Value and Reference Parameters and Memory Allocation
1. This section discusses in detail how memory is manipulated with respect to both value
and reference parameters. Three programs are presented with different scenarios and
with figures that demonstrate how the parameters are modified. Guide students through
one or more of these programs (Examples 7-7 and 7-8) and the accompanying figures.
Encourage them to study the programs more on their own.
Teaching
Tip
There is a great deal of useful material to cover in these three programs. It might
be a good idea to divide the students into groups, and have them walk through
one of the programs together. Then, ask them to present the key issues regarding
parameter passing in the program they reviewed.
C++ Programming: Program Design Including Data Structures, Fourth Edition
7-5
Reference Parameters and Value-Returning Parameters
1. Note that you can use reference parameters in a value-returning function, but this
approach is not recommended. By definition, a value-returning function returns a single
value; this value is returned via the return statement. Explain that if a function needs to
return more than one value, one should change it to a void function and use the
appropriate reference parameters to return the values.
Scope of an Identifier
1. Define the term scope and explain how it is used to determine where an identifier may
be accessed in a program.
2. Explain the difference between a local identifier and a global identifier.
3. Discuss scope rules with respect to global and local identifiers, nested blocks, and
functions.
4. Step through the program in this section and use Table 7-1 to discuss the visibility of
the identifiers in the program.
5. Describe the purpose of the scope resolution operator.
6. Describe the purpose of the reserved word extern.
Teaching
Tip
Note that global variables would not typically be declared between function
definitions, as they are in the program in this section. Discuss good
programming practices with respect to declaring variable and function
prototypes before main. Briefly discuss the typical use of the word extern
for accessing variables in another source file.
Quick Quiz 2
1. A(n) ____________________ identifier is declared outside of every function definition.
Answer: global
2. Define the scope of an identifier.
Answer: The scope refers to where an identifier is accessible (visible) in a program.
3. True or False: The scope of a function name is the same as the scope of a global
identifier.
Answer: True
C++ Programming: Program Design Including Data Structures, Fourth Edition
7-6
4. True or False: C++ allows nested functions.
Answer: False
Global Variables, Named Constants, and Side Effects
1. Discuss the side effects associated with using global variables in a program.
2. Review why named constants are typically declared as global variables.
Teaching
Tip
This chapter mentions that global variables can cause problems because they can
be modified anywhere in the program. Discuss specific situations in which this
might be an issue, for example, when alternating function calls in which the same
global variable is used.
Static and Automatic Variables
1. Explain the difference between an automatic variable and a static variable.
2. Discuss the syntax, scope, and initialization of static variables.
3. Use Example 7-9 to illustrate a typical use of a static variable.
Teaching
Tip
Note that static and global variables are both kept in memory as long as the
program executes. Explain why using a local static variable is usually preferable
to using a global variable.
Function Overloading: An Introduction
1. Define function overloading and explain that two or more functions may have the same
name if their formal parameter lists are different.
2. Explain that when two or more functions have the same name, the compiler determines
the correct function by its parameter list.
Teaching
Tip
Overloading is an important concept. You have probably introduced some form
of overloading in previous chapters and might want to revisit some of these
examples, such as operator overloading with the equality operator. Ask students
if they find the function/operator overloading in the C++ libraries useful, and if
so, why.
C++ Programming: Program Design Including Data Structures, Fourth Edition
7-7
Functions with Default Parameters
1. Discuss the rules regarding the use of default parameters.
2. Emphasize that calls to functions with default parameters do not necessarily have to
include all of the actual parameters; however, they must follow the ordering in the rules
discussed above.
3. Illustrate the use of default parameters with Example 7-10.
4. Encourage students to study and execute the Programming Examples (“Classify
Numbers” and “Data Comparison”) to review the concepts discussed in this chapter.
Class Discussion Topics
1. If reference parameters can be used in any function, why use value parameters at all?
How are value parameters useful in processing data in a program?
2. Why is it generally not wise to combine value-returning functions with reference
parameters?
3. Ask students to think of situations in which default parameters might be useful.
Additional Projects
1. Write a program that calculates how much money you are spending on average per day
in a week. The program will calculate the total average, as well as the average of what
you spend in the following categories: food, clothing, school-related expenses, and
outside entertainment. You will ask the user how much he/she spends in each category
for each day and keep a running total for each category. Use static variables to keep
track of these amounts, as you will revisit a function containing the loop structure(s) for
each day. You will also need an average function that calculates all of the averages.
Organize the main program to call input and output functions. The input function will
be responsible for updating the totals, and the output function will calculate and display
the results. Note that these functions will most likely call other functions to accomplish
tasks. Use value and reference parameters as necessary.
2. Write a program that simulates a questionnaire to find a roommate. You will ask the
user various questions that might determine a suitable match, such as their age, gender,
smoking preference, sleeping habits, pets, etc. Use an overloaded function, called
match, to determine if their preferences match your own. The match functions will
take a string, Boolean, floating-point, or integer parameter depending on the question,
and return a Boolean value. The questions themselves will be contained in a function,
which returns a Boolean value indicating whether the roommate is a match (depending
on an acceptable number of matches on the questionnaire).
C++ Programming: Program Design Including Data Structures, Fourth Edition
7-8
Additional Resources
1. Tutorial: Functions II:
www.cplusplus.com/doc/tutorial/functions2.html
2. C++ Notes: Function Reference Parameters:
www.fredosaurus.com/notes-cpp/functions/refparams.html
3. Static: The Multipurpose Keyword:
www.cprogramming.com/tutorial/statickeyword.html
4. C++ Tutorial: Function Overloading:
http://cplus.about.com/od/beginnerctutorial/l/aa061602a.htm
Key Terms
 Automatic variable: variable for which memory is allocated at block entry and
deallocated at block exit
 Different formal parameter lists: when two or more functions have a different number
of formal parameters, or if they have the same number of parameters, the data type of
the parameters differs in at least one position
 External variable: global variable declared within a function using the extern
reserved word
 Function overloading (overloading a function name): creating several functions with
the same name
 Global identifier: identifier declared outside of every function definition
 Local identifier: identifier declared within a function (or block)
 Local variables: variables declared in the body of a function (or block) for use only
within that block
 Nested block: block declared within another block
 Reference parameter: formal parameter that receives the location (memory address) of
the corresponding actual parameter
 Scope: refers to where an identifier is accessible (visible) in a program
 Scope resolution operator: ::, by using the scope resolution operator, a global
variable declared before the definition of a function (block) can be accessed by the
function (or block), even if the function (or block) has an identifier with the same name
as the variable
 Signature (of a function): consists of the function name and its formal parameter list
 Static variable: variable for which memory remains allocated as long as the program
executes
 Value parameter: formal parameter that receives a copy of the content of the
corresponding actual parameter
 Void function: function that has no data type
Download