Functions and An To Recursion: 2006 Pearson Education, Inc. All Rights Reserved

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 77

1

6
Functions and an
Introduction
to Recursion
 2006 Pearson Education, Inc. All rights reserved.
2

6.1 Introduction
6.2 Program Components in C++
6.3 Math Library Functions
6.4 Function Definitions with Multiple Parameters
6.5 Function Prototypes and Argument Coercion
6.6 C++ Standard Library Header Files
6.7 Case Study: Random Number Generation
6.8 Case Study: Game of Chance and Introducing enum
6.9 Storage Classes
6.10 Scope Rules
6.11 Function Call Stack and Activation Records
6.12 Functions with Empty Parameter Lists

 2006 Pearson Education, Inc. All rights reserved.


3

6.13 Inline Functions


6.14 References and Reference Parameters
6.15 Default Arguments
6.16 Unary Scope Resolution Operator
6.17 Function Overloading
6.18 Function Templates
6.19 Recursion
6.20 Example Using Recursion: Fibonacci Series
6.21 Recursion vs. Iteration
6.22 (Optional) Software Engineering Case Study:
Identifying Class Operations in the ATM System
6.23 Wrap-Up

 2006 Pearson Education, Inc. All rights reserved.


4

6.1 Introduction
• Divide and conquer technique
– Construct a large program from small, simple pieces (e.g.,
components)
• Functions
– Facilitate the design, implementation, operation and
maintenance of large programs
• C++ Standard Library math functions

 2006 Pearson Education, Inc. All rights reserved.


5

6.2 Program Components in C++


• C++ Standard Library
– Rich collection of functions for performing common
operations, such as:
• Mathematical calculations
• String manipulations
• Character manipulations
• Input/Output
• Error checking
– Provided as part of the C++ programming
environment

 2006 Pearson Education, Inc. All rights reserved.


6

6.2 Program Components in C++ (Cont.)

• Functions
– Called methods or procedures in other languages
– Allow programmers to modularize a program by
separating its tasks into self-contained units
• Statements in function bodies are written only once
– Reused from perhaps several locations in a program
– Avoid repeating code
• Enable the divide-and-conquer approach
• Reusable in other programs

 2006 Pearson Education, Inc. All rights reserved.


7

6.2 Program Components in C++ (cont.)

• Functions (Cont.)
– A function is invoked by a function call
• Called function either returns a result or simply returns to
the caller
• Function calls form hierarchical relationships

 2006 Pearson Education, Inc. All rights reserved.


8

Fig. 6.1 | Hierarchical boss function/worker function relationship.

 2006 Pearson Education, Inc. All rights reserved.


9

6.3 Math Library Functions


• Global functions
– Do not belong to a particular class
– Have function prototypes placed in header files
• Can be reused in any program that includes the header file
and that can link to the function’s object code
– Example: sqrt in <cmath> header file
• sqrt( 900.0 )
• All functions in <cmath> are global functions

 2006 Pearson Education, Inc. All rights reserved.


10

Function Description Example

ceil( x ) rounds x to the smallest ceil( 9.2 ) is 10.0


integer not less than x ceil( -9.8 ) is -9.0
cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0
(x in radians)
exp( x ) exponential function ex exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
fabs( x ) absolute value of x fabs( 5.1 ) is 5.1
fabs( 0.0 ) is 0.0
fabs( -8.76 ) is 8.76
floor( x ) rounds x to the largest integer not floor( 9.2 ) is 9.0
greater than x floor( -9.8 ) is -10.0
fmod( x, y ) remainder of x/y as a floating-point fmod( 2.6, 1.2 ) is 0.2
number
log( x ) natural logarithm of x log( 2.718282 ) is 1.0
(base e) log( 7.389056 ) is 2.0

log10( x ) logarithm of x (base 10) log10( 10.0 ) is 1.0


log10( 100.0 ) is 2.0
pow( x, y ) x raised to power y (xy) pow( 2, 7 ) is 128
pow( 9, .5 ) is 3
sin( x ) trigonometric sine of x sin( 0.0 ) is 0
(x in radians)
sqrt( x ) square root of x (where x is a sqrt( 9.0 ) is 3.0
nonnegative value)
tan( x ) trigonometric tangent of x tan( 0.0 ) is 0
(x in radians)

Fig. 6.2 | Math library functions.

 2006 Pearson Education, Inc. All rights reserved.


11
6.4 Function Definitions with Multiple
Parameters
• Multiple parameters
– Functions often require more than one piece of information
to perform their tasks
– Specified in both the function prototype and the function
header as a comma-separated list of parameters

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 6.3: GradeBook.h
12
2 // Definition of class GradeBook that finds the maximum of three grades.
Outline
3 // Member functions are defined in GradeBook.cpp
4 #include <string> // program uses C++ standard string class
5 using std::string;
6 GradeBook.h
7 // GradeBook class definition
8 class GradeBook (1 of 1)
9 {
10 public:
11 GradeBook( string ); // constructor initializes course name
12 void setCourseName( string ); // function to set the course name
13 string getCourseName(); // function to retrieve the course name
14 void displayMessage(); // display a welcome message
15 void inputGrades(); // input three grades from user
16 void displayGradeReport(); // display a report based on the grades
17 int maximum( int, int, int ); // determine max of 3 values
18 private:
19 string courseName; // course name for this GradeBook Prototype for a member function
20 int maximumGrade; // maximum of three grades that takes three arguments
21 }; // end class GradeBook
Data member to store maximum grade

 2006 Pearson Education,


Inc. All rights reserved.
1 // Fig. 6.4: GradeBook.cpp
13
2
3
// Member-function definitions for class GradeBook that
// determines the maximum of three grades.
Outline
4 #include <iostream>
5 using std::cout;
6 using std::cin;
GradeBook.cpp
7 using std::endl;
8
9 #include "GradeBook.h" // include definition of class GradeBook
(1 of 3)
10
11 // constructor initializes courseName with string supplied as argument;
12 // initializes studentMaximum to 0
13 GradeBook::GradeBook( string name )
14 {
15 setCourseName( name ); // validate and store courseName
16 maximumGrade = 0; // this value will be replaced by the maximum grade
17 } // end GradeBook constructor
18
19 // function to set the course name; limits name to 25 or fewer characters
20 void GradeBook::setCourseName( string name )
21 {
22 if ( name.length() <= 25 ) // if name has 25 or fewer characters
23 courseName = name; // store the course name in the object
24 else // if name is longer than 25 characters
25 { // set courseName to first 25 characters of parameter name
26 courseName = name.substr( 0, 25 ); // select first 25 characters
27 cout << "Name \"" << name << "\" exceeds maximum length (25).\n"
28 << "Limiting courseName to first 25 characters.\n" << endl;
29 } // end if...else
30 } // end function setCourseName

 2006 Pearson Education,


Inc. All rights reserved.
31
14
32 // function to retrieve the course name
33 string GradeBook::getCourseName()
Outline
34 {
35 return courseName;
36 } // end function getCourseName
GradeBook.cpp
37
38 // display a welcome message to the GradeBook user
39 void GradeBook::displayMessage() (2 of 3)
40 {
41 // this statement calls getCourseName to get the
42 // name of the course this GradeBook represents
43 cout << "Welcome to the grade book for\n" << getCourseName() << "!\n"
44 << endl;
45 } // end function displayMessage
46
47 // input three grades from user; determine maximum
48 void GradeBook::inputGrades()
49 {
50 int grade1; // first grade entered by user
51 int grade2; // second grade entered by user
52 int grade3; // third grade entered by user
53
54 cout << "Enter three integer grades: ";
Call to function maximum
55 cin >> grade1 >> grade2 >> grade3;
56
passes three arguments
57 // store maximum in member studentMaximum
58 maximumGrade = maximum( grade1, grade2, grade3 );
59 } // end function inputGrades

 2006 Pearson Education,


Inc. All rights reserved.
60
15
61 // returns the maximum of its three integer parameters
Outline
62 int GradeBook::maximum( int x, int y, int z )
63 { maximum member function header
64 int maximumValue = x; // assume x is the largest to start
65 GradeBook.cpp
Comma-separated parameter list
66 // determine whether y is greater than maximumValue
67 if ( y > maximumValue ) (3 of 3)
68 maximumValue = y; // make y the new maximumValue
69
70 // determine whether z is greater than maximumValue
71 if ( z > maximumValue )
72 maximumValue = z; // make z the new maximumValue
73
74 return maximumValue;
75 } // end function maximum Returning a value to the caller
76
77 // display a report based on the grades entered by user
78 void GradeBook::displayGradeReport()
79 {
80 // output maximum of grades entered
81 cout << "Maximum of grades entered: " << maximumGrade << endl;
82 } // end function displayGradeReport

 2006 Pearson Education,


Inc. All rights reserved.
1 // Fig. 6.5: fig06_05.cpp 16
2
3
// Create GradeBook object, input grades and display grade report.
#include "GradeBook.h" // include definition of class GradeBook
Outline
4
5 int main()
6 {
fig06_05.cpp
7 // create GradeBook object
8 GradeBook myGradeBook( "CS101 C++ Programming" );
9
(1 of 1)
10 myGradeBook.displayMessage(); // display welcome message
11 myGradeBook.inputGrades(); // read grades from user
12 myGradeBook.displayGradeReport(); // display report based on grades
13 return 0; // indicate successful termination
14 } // end main

Welcome to the grade book for


CS101 C++ Programming!

Enter three integer grades: 86 67 75


Maximum of grades entered: 86

Welcome to the grade book for


CS101 C++ Programming!

Enter three integer grades: 67 86 75


Maximum of grades entered: 86

Welcome to the grade book for


CS101 C++ Programming!

Enter three integer grades: 67 75 86


Maximum of grades entered: 86
 2006 Pearson Education,
Inc. All rights reserved.
17
6.4 Function Definitions with Multiple
Parameters (Cont.)
• Compiler uses a function prototype to:
– Check that calls to the function contain the correct number
and types of arguments in the correct order
– Ensure that the value returned by the function is used
correctly in the expression that called the function
• Each argument must be consistent with the type
of the corresponding parameter
– Parameters are also called formal parameters

 2006 Pearson Education, Inc. All rights reserved.


18
6.4 Function Definitions with Multiple
Parameters (Cont.)
• Three ways to return control to the calling
statement:
– If the function does not return a result:
• Program flow reaches the function-ending right brace or
• Program executes the statement return;
– If the function does return a result:
• Program executes the statement return expression;
– expression is evaluated and its value is returned to the
caller

 2006 Pearson Education, Inc. All rights reserved.


19
6.5 Function Prototypes and Argument
Coercion
• Function prototype
– Also called a function declaration
– Indicates to the compiler:
• Name of the function
• Type of data returned by the function
• Parameters the function expects to receive
– Number of parameters
– Types of those parameters
– Order of those parameters

 2006 Pearson Education, Inc. All rights reserved.


20
6.5 Function Prototypes and Argument
Coercion (Cont.)
• Function signature (or simply signature)
– The portion of a function prototype that includes the name
of the function and the types of its arguments
• Does not specify the function’s return type
– Functions in the same scope must have unique signatures
• The scope of a function is the region of a program in which
the function is known and accessible

 2006 Pearson Education, Inc. All rights reserved.


21
6.5 Function Prototypes and Argument
Coercion (Cont.)
• Argument Coercion
– Forcing arguments to the appropriate types specified by
the corresponding parameters
• For example, calling a function with an integer argument,
even though the function prototype specifies a double
argument
– The function will still work correctly

 2006 Pearson Education, Inc. All rights reserved.


22
6.5 Function Prototypes and Argument
Coercion (Cont.)
• C++ Promotion Rules
– Indicate how to convert between types without losing
data
– Apply to expressions containing values of two or more data
types
• Such expressions are also referred to as mixed-type
expressions
• Each value in the expression is promoted to the “highest”
type in the expression
– Temporary version of each value is created and used for
the expression
• Original values remain unchanged

 2006 Pearson Education, Inc. All rights reserved.


23
6.5 Function Prototypes and Argument
Coercion (Cont.)
• C++ Promotion Rules (Cont.)
– Promotion also occurs when the type of a function
argument does not match the specified parameter type
• Promotion is as if the argument value were being assigned
directly to the parameter variable
– Converting a value to a lower fundamental type
• Will likely result in the loss of data or incorrect values
• Can only be performed explicitly
– By assigning the value to a variable of lower type (some
compilers will issue a warning in this case) or
– By using a cast operator

 2006 Pearson Education, Inc. All rights reserved.


24

Data types
long double
double
float
unsigned long int (synonymous with unsigned long)
long int (synonymous with long)
unsigned int (synonymous with unsigned)
int
unsigned short int (synonymous with unsigned short)
short int (synonymous with short)
unsigned char
char
bool

Fig. 6.6 | Promotion hierarchy for fundamental data types.

 2006 Pearson Education, Inc. All rights reserved.


25

6.6 C++ Standard Library Header Files

• C++ Standard Library header files


– Each contains a portion of the Standard Library
• Function prototypes for the related functions
• Definitions of various class types and functions
• Constants needed by those functions
– “Instruct” the compiler on how to interface with library
and user-written components
– Header file names ending in .h
• Are “old-style” header files
• Superseded by the C++ Standard Library header files

 2006 Pearson Education, Inc. All rights reserved.


26

C++ Standard Explanation


Library header file
<iostream> Contains function prototypes for the C++ standard input and
standard output functions, introduced in Chapter 2, and is
covered in more detail in Chapter 15, Stream Input/Output. This
header file replaces header file <iostream.h>.
<iomanip> Contains function prototypes for stream manipulators that
format streams of data. This header file is first used in
Section 4.9 and is discussed in more detail in Chapter 15, Stream
Input/Output. This header file replaces header file
<iomanip.h>.
<cmath> Contains function prototypes for math library functions
(discussed in Section 6.3). This header file replaces header file
<math.h>.
<cstdlib> Contains function prototypes for conversions of numbers to text,
text to numbers, memory allocation, random numbers and
various other utility functions. Portions of the header file are
covered in Section 6.7; Chapter 11, Operator Overloading;
String and Array Objects; Chapter 16, Exception Handling;
Chapter 19, Web Programming; Chapter 22, Bits, Characters,
C-Strings and structs; and Appendix E, C Legacy Code
Topics. This header file replaces header file <stdlib.h>.

Fig. 6.7 | C++ Standard Library header files. (Part 1 of 4)

 2006 Pearson Education, Inc. All rights reserved.


27

C++ Standard Explanation


Library header file
<ctime> Contains function prototypes and types for manipulating the time and
date. This header file replaces header file <time.h>. This header file
is used in Section 6.7.
<vector>, These header files contain classes that implement the C++ Standard
<list>, Library containers. Containers store data during a program’s
<deque>,
<queue>, execution. The <vector> header is first introduced in Chapter 7,
<stack>, Arrays and Vectors. We discuss all these header files in Chapter 23,
<map>, Standard Template Library (STL).
<set>,
<bitset>
<cctype> Contains function prototypes for functions that test characters for
certain properties (such as whether the character is a digit or a
punctuation), and function prototypes for functions that can be used to
convert lowercase letters to uppercase letters and vice versa. This
header file replaces header file <ctype.h>. These topics are
discussed in Chapter 8, Pointers and Pointer-Based Strings, and
Chapter 22, Bits, Characters, C-Strings and structs.
<cstring> Contains function prototypes for C-style string-processing functions.
This header file replaces header file <string.h>. This header file is
used in Chapter 11, Operator Overloading; String and Array Objects.

Fig. 6.7 | C++ Standard Library header files. (Part 2 of 4)

 2006 Pearson Education, Inc. All rights reserved.


28

C++ Standard
Explanation
Library header file
<typeinfo> Contains classes for runtime type identification (determining
data types at execution time). This header file is discussed in
Section 13.8.
<exception>, These header files contain classes that are used for exception
<stdexcept> handling (discussed in Chapter 16).
<memory> Contains classes and functions used by the C++ Standard
Library to allocate memory to the C++ Standard Library
containers. This header is used in Chapter 16, Exception
Handling.
<fstream> Contains function prototypes for functions that perform input
from files on disk and output to files on disk (discussed in
Chapter 17, File Processing). This header file replaces header file
<fstream.h>.
<string> Contains the definition of class string from the C++ Standard
Library (discussed in Chapter 18).
<sstream> Contains function prototypes for functions that perform input
from strings in memory and output to strings in memory
(discussed in Chapter 18, Class string and String Stream
Processing).
<functional> Contains classes and functions used by C++ Standard Library
algorithms. This header file is used in Chapter 23.

Fig. 6.7 | C++ Standard Library header files. (Part 3 of 4)

 2006 Pearson Education, Inc. All rights reserved.


29

C++ Standard Library Explanation


header file
<iterator> Contains classes for accessing data in the C++ Standard Library
containers. This header file is used in Chapter 23, Standard Template
Library (STL).
<algorithm> Contains functions for manipulating data in C++ Standard Library
containers. This header file is used in Chapter 23.
<cassert> Contains macros for adding diagnostics that aid program debugging.
This replaces header file <assert.h> from pre-standard C++. This
header file is used in Appendix F, Preprocessor.
<cfloat> Contains the floating-point size limits of the system. This header file
replaces header file <float.h>.
<climits> Contains the integral size limits of the system. This header file replaces
header file <limits.h>.
<cstdio> Contains function prototypes for the C-style standard input/output
library functions and information used by them. This header file
replaces header file <stdio.h>.
<locale> Contains classes and functions normally used by stream processing to
process data in the natural form for different languages (e.g.,
monetary formats, sorting strings, character presentation, etc.).
<limits> Contains classes for defining the numerical data type limits on each
computer platform.
<utility> Contains classes and functions that are used by many C++ Standard
Library header files.

Fig. 6.7 | C++ Standard Library header files. (Part 4 of 4)

 2006 Pearson Education, Inc. All rights reserved.


30
6.7 Case Study: Random Number
Generation
• C++ Standard Library function rand
– Introduces the element of chance into computer applications
– Example
• i = rand();
– Generates an unsigned integer between 0 and RAND_MAX (a
symbolic constant defined in header file <cstdlib>)
– Function prototype for the rand function is in <cstdlib>

 2006 Pearson Education, Inc. All rights reserved.


31
6.7 Case Study: Random Number
Generation (Cont.)
• To produce integers in a specific range, use the modulus
operator (%) with rand
– Example
• rand() % 6;
– Produces numbers in the range 0 to 5
– This is called scaling, 6 is the scaling factor
– Shifting can move the range to 1 to 6
• 1 + rand() % 6;

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 6.8: fig06_08.cpp
32
2 // Shifted and scaled random integers.
Outline
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6 fig06_08.cpp
7 #include <iomanip>
8 using std::setw; (1 of 2)
9
10 #include <cstdlib> // contains function prototype for rand
11 using std::rand;
12
#include and using for function rand
13 int main()
14 {
15 // loop 20 times
16 for ( int counter = 1; counter <= 20; counter++ )
17 {
18 // pick random number from 1 to 6 and output it
19 cout << setw( 10 ) << ( 1 + rand() % 6 );

Calling function rand

 2006 Pearson Education,


Inc. All rights reserved.
20
33
21 // if counter is divisible by 5, start a new line of output
Outline
22 if ( counter % 5 == 0 )
23 cout << endl;
24 } // end for
25 fig06_08.cpp
26 return 0; // indicates successful termination
27 } // end main (2 of 2)
6 6 5 5 6
5 1 1 5 3
6 6 2 4 2
6 2 3 4 1

 2006 Pearson Education,


Inc. All rights reserved.
1 // Fig. 6.9: fig06_09.cpp
34
2
3
// Roll a six-sided die 6,000,000 times.
#include <iostream>
Outline
4 using std::cout;
5 using std::endl;
6
fig06_09.cpp
7 #include <iomanip>
8 using std::setw;
9
(1 of 3)
10 #include <cstdlib> // contains function prototype for rand
11 using std::rand;
12
13 int main()
14 {
15 int frequency1 = 0; // count of 1s rolled
16 int frequency2 = 0; // count of 2s rolled
17 int frequency3 = 0; // count of 3s rolled
18 int frequency4 = 0; // count of 4s rolled
19 int frequency5 = 0; // count of 5s rolled
20 int frequency6 = 0; // count of 6s rolled
21
22 int face; // stores most recently rolled value
23
24 // summarize results of 6,000,000 rolls of a die
25 for ( int roll = 1; roll <= 6000000; roll++ )
26 {
27 face = 1 + rand() % 6; // random number from 1 to 6

Scaling and shifting the value


produced by function rand  2006 Pearson Education,
Inc. All rights reserved.
28
35
29
30
// determine roll value 1-6 and increment appropriate counter
switch ( face )
Outline
31 {
32 case 1:
33 ++frequency1; // increment the 1s counter
fig06_09.cpp
34 break;
35 case 2:
36 ++frequency2; // increment the 2s counter
(2 of 3)
37 break;
38 case 3:
39 ++frequency3; // increment the 3s counter
40 break;
41 case 4:
42 ++frequency4; // increment the 4s counter
43 break;
44 case 5:
45 ++frequency5; // increment the 5s counter
46 break;
47 case 6:
48 ++frequency6; // increment the 6s counter
49 break;
50 default: // invalid value
51 cout << "Program should never get here!";
52 } // end switch
53 } // end for

 2006 Pearson Education,


Inc. All rights reserved.
54
36
55
56
cout << "Face" << setw( 13 ) << "Frequency" << endl; // output headers
cout << " 1" << setw( 13 ) << frequency1
Outline
57 << "\n 2" << setw( 13 ) << frequency2
58 << "\n 3" << setw( 13 ) << frequency3
59 << "\n 4" << setw( 13 ) << frequency4
60 << "\n 5" << setw( 13 ) << frequency5 fig06_09.cpp
61 << "\n 6" << setw( 13 ) << frequency6 << endl;
62 return 0; // indicates successful termination (3 of 3)
63 } // end main

Face Frequency
1 999702
2 1000823
3 999378
4 998898
5 1000777
6 1000422 Each face value appears approximately 1,000,000 times

 2006 Pearson Education,


Inc. All rights reserved.
37
6.7 Case Study: Random Number
Generation (Cont.)
• Function rand
– Generates pseudorandom numbers
– The same sequence of numbers repeats itself each time the
program executes
• Randomizing
– Conditioning a program to produce a different sequence of
random numbers for each execution
• C++ Standard Library function srand
– Takes an unsigned integer argument
– Seeds the rand function to produce a different sequence of
random numbers

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 6.10: fig06_10.cpp
38
2 // Randomizing die-rolling program.
Outline
3 #include <iostream>
4 using std::cout;
5 using std::cin;
6 using std::endl; fig06_10.cpp
7
8 #include <iomanip> (1 of 2)
9 using std::setw;
10
11 #include <cstdlib> // contains prototypes for functions srand and rand
12 using std::rand;
13 using std::srand;
14
15 int main() using statement for function srand
16 {
17 unsigned seed; // stores the seed entered by the user
18
19 cout << "Enter seed: "; Data type unsigned is short for unsigned int
20 cin >> seed;
21 srand( seed ); // seed random number generator
22

Passing seed to srand to randomize the program

 2006 Pearson Education,


Inc. All rights reserved.
23 // loop 10 times
39
24
25
for ( int counter = 1; counter <= 10; counter++ )
{
Outline
26 // pick random number from 1 to 6 and output it
27 cout << setw( 10 ) << ( 1 + rand() % 6 );
28
fig06_10.cpp
29 // if counter is divisible by 5, start a new line of output
30 if ( counter % 5 == 0 )
31 cout << endl; (2 of 2)
32 } // end for
33
34 return 0; // indicates successful termination
35 } // end main

Enter seed: 67
6 1 4 6 2
1 6 1 6 4

Enter seed: 432 Program outputs show that each


4 6 3 1 6
3 1 5 4 2 unique seed value produces a different
sequence of random numbers
Enter seed: 67
6 1 4 6 2
1 6 1 6 4

 2006 Pearson Education,


Inc. All rights reserved.
40
6.7 Case Study: Random Number
Generation (Cont.)
• To randomize without having to enter a seed each
time
– srand( time( 0 ) );
• This causes the computer to read its clock to obtain the seed
value
– Function time (with the argument 0)
• Returns the current time as the number of seconds since
January 1, 1970 at midnight Greenwich Mean Time (GMT)
• Function prototype for time is in <ctime>

 2006 Pearson Education, Inc. All rights reserved.


41
6.7 Case Study: Random Number
Generation (Cont.)
• Scaling and shifting random numbers
– To obtain random numbers in a desired range, use a
statement like
number = shiftingValue + rand() % scalingFactor;
• shiftingValue is equal to the first number in the desired range
of consecutive integers
• scalingFactor is equal to the width of the desired range of
consecutive integers
– number of consecutive integers in the range

 2006 Pearson Education, Inc. All rights reserved.


42
6.8 Case Study: Game of Chance and
Introducing enum
• Enumeration
– A set of integer constants represented by identifiers
• The values of enumeration constants start at 0, unless
specified otherwise, and increment by 1
• The identifiers in an enum must be unique, but separate
enumeration constants can have the same integer value
– Defining an enumeration
• Keyword enum
• A type name
• Comma-separated list of identifier names enclosed in braces
• Example
– enum Months { JAN = 1, FEB, MAR, APR };

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 6.11: fig06_11.cpp
43
2 // Craps simulation.
Outline
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6 fig06_11.cpp
7 #include <cstdlib> // contains prototypes for functions srand and rand
8 using std::rand; (1 of 4)
9 using std::srand;
10
11 #include <ctime> // contains prototype for function time
12 using std::time;
13 #include and using for function time
14 int rollDice(); // rolls dice, calculates amd displays sum
15
16 int main()
17 {
18 // enumeration with constants that represent the game status
19 enum Status { CONTINUE, WON, LOST }; // all caps in constants
20
Enumeration to keep track of the game status
21 int myPoint; // point if no win or loss on first roll
22 Status gameStatus; // can contain CONTINUE, WON or LOST
23
24 Declaring
// randomize random number generator a variable
using current timeof the user-defined enumeration type
25 srand( time( 0 ) );
26
27 int sumOfDice = rollDice(); //Seeding the random
first roll number
of the dice generator with the current time

 2006 Pearson Education,


Inc. All rights reserved.
28
44
29
30
// determine game status and point (if needed) based on first roll
switch ( sumOfDice )
Outline
31 {
32 case 7: // win with 7 on first roll
33 case 11: // win with 11 on first roll
fig06_11.cpp
34 gameStatus = WON;
35 break;
36 case 2: // lose with 2 on first roll Assigning an enumeration constant(2toof 4)
gameStatus
37 case 3: // lose with 3 on first roll
38 case 12: // lose with 12 on first roll
39 gameStatus = LOST;
40 break;
41 default: // did not win or lose, so remember point
42 gameStatus = CONTINUE; // game is not over
43 myPoint = sumOfDice; // remember the point
44 cout << "Point is " << myPoint << endl;
45 break; // optional at end of switch
46 } // end switch
Comparing a variable of an enumeration
47
48 // while game is not complete
type to an enumeration constant
49 while ( gameStatus == CONTINUE ) // not WON or LOST
50 {
51 sumOfDice = rollDice(); // roll dice again
52

 2006 Pearson Education,


Inc. All rights reserved.
53 // determine game status
45
54
55
if ( sumOfDice == myPoint ) // win by making point
gameStatus = WON;
Outline
56 else
57 if ( sumOfDice == 7 ) // lose by rolling 7 before point
58 gameStatus = LOST;
fig06_11.cpp
59 } // end while
60
61 // display won or lost message
(3 of 4)
62 if ( gameStatus == WON )
63 cout << "Player wins" << endl;
64 else
65 cout << "Player loses" << endl;
66
67 return 0; // indicates successful termination
68 } // end main
69
70 // roll dice, calculate sum and display results
71 int rollDice()
72 { Function that performs the task of rolling the dice
73 // pick random die values
74 int die1 = 1 + rand() % 6; // first die roll
75 int die2 = 1 + rand() % 6; // second die roll
76
77 int sum = die1 + die2; // compute sum of die values

 2006 Pearson Education,


Inc. All rights reserved.
78
46
79
80
// display results of this roll
cout << "Player rolled " << die1 << " + " << die2
Outline
81 << " = " << sum << endl;
82 return sum; // end function rollDice
83 } // end function rollDice
fig06_11.cpp
Player rolled 2 + 5 = 7
Player wins
(4 of 4)

Player rolled 6 + 6 = 12
Player loses

Player rolled 3 + 3 = 6
Point is 6
Player rolled 5 + 3 = 8
Player rolled 4 + 5 = 9
Player rolled 2 + 1 = 3
Player rolled 1 + 5 = 6
Player wins

Player rolled 1 + 3 = 4
Point is 4
Player rolled 4 + 6 = 10
Player rolled 2 + 4 = 6
Player rolled 6 + 4 = 10
Player rolled 2 + 3 = 5
Player rolled 2 + 4 = 6
Player rolled 1 + 1 = 2
Player rolled 4 + 4 = 8
Player rolled 4 + 3 = 7
Player loses

 2006 Pearson Education,


Inc. All rights reserved.
47

6.9 Storage Classes


• Each identifier has several attributes
– Name, type, size and value
– Also storage class, scope and linkage
• C++ provides five storage-class specifiers:
– auto, register, extern, mutable and static
• Identifier’s storage class
– Determines the period during which that identifier exists in
memory
• Identifier’s scope
– Determines where the identifier can be referenced in a
program

 2006 Pearson Education, Inc. All rights reserved.


48

6.9 Storage Classes (Cont.)


• Identifier’s linkage
– Determines whether an identifier is known only in the
source file where it is declared or across multiple files that
are compiled, then linked together
• An identifier’s storage-class specifier helps
determine its storage class and linkage

 2006 Pearson Education, Inc. All rights reserved.


49

6.9 Storage Classes (Cont.)


• Automatic storage class
– Declared with keywords auto and register
– Automatic variables
• Created when program execution enters block in which they
are defined
• Exist while the block is active
• Destroyed when the program exits the block
– Only local variables and parameters can be of automatic
storage class
• Such variables normally are of automatic storage class

 2006 Pearson Education, Inc. All rights reserved.


50

Performance Tip 6.2


The storage-class specifier register can be
placed before an automatic variable declaration to
suggest that the compiler maintain the variable in
one of the computer’s high-speed hardware
registers rather than in memory. If intensely used
variables such as counters or totals are maintained
in hardware registers, the overhead of repeatedly
loading the variables from memory into the
registers and storing the results back into memory
is eliminated.

 2006 Pearson Education, Inc. All rights reserved.


51

6.9 Storage Classes (Cont.)


• Storage-class specifier auto
– Explicitly declares variables of automatic storage class
– Local variables are of automatic storage class by default
• So keyword auto rarely is used
• Storage-class specifier register
– Data in the machine-language version of a program is
normally loaded into registers for calculations and other
processing
• Compiler tries to store register storage class variables in a
register
– The compiler might ignore register declarations
• May not be sufficient registers for the compiler to use

 2006 Pearson Education, Inc. All rights reserved.


52

Performance Tip 6.3

Often, register is unnecessary. Today’s


optimizing compilers are capable of recognizing
frequently used variables and can decide to place
them in registers without needing a register
declaration from the programmer.

 2006 Pearson Education, Inc. All rights reserved.


53

6.9 Storage Classes (Cont.)


• Static storage class
– Declared with keywords extern and static
– Static-storage-class variables
• Exist from the point at which the program begins execution
• Initialized once when their declarations are encountered
• Last for the duration of the program
– Static-storage-class functions
• The name of the function exists when the program begins execution,
just as for all other functions
– However, even though the variables and the function names exist
from the start of program execution, this does not mean that
these identifiers can be used throughout the program.

 2006 Pearson Education, Inc. All rights reserved.


54

6.9 Storage Classes (Cont.)


• Two types of identifiers with static storage class
– External identifiers
• Such as global variables and global function names
– Local variables declared with the storage class specifier static
• Global variables
– Created by placing variable declarations outside any class or
function definition
– Retain their values throughout the execution of the program
– Can be referenced by any function that follows their declarations
or definitions in the source file

 2006 Pearson Education, Inc. All rights reserved.


55

6.9 Storage Classes (Cont.)


• Local variables declared with keyword static
– Known only in the function in which they are declared
– Retain their values when the function returns to its caller
• Next time the function is called, the static local variables
contain the values they had when the function last completed
– If numeric variables of the static storage class are not
explicitly initialized by the programmer
• They are initialized to zero

 2006 Pearson Education, Inc. All rights reserved.


56

6.10 Scope Rules


• Scope
– Portion of the program where an identifier can be used
– Four scopes for an identifier
• Function scope
• File scope
• Block scope
• Function-prototype scope

 2006 Pearson Education, Inc. All rights reserved.


57

6.10 Scope Rules (Cont.)


• File scope
– For an identifier declared outside any function or class
• Such an identifier is “known” in all functions from the point at
which it is declared until the end of the file
– Global variables, function definitions and function prototypes
placed outside a function all have file scope
• Function scope
– Labels (identifiers followed by a colon such as start:) are the
only identifiers with function scope
• Can be used anywhere in the function in which they appear
• Cannot be referenced outside the function body
• Labels are implementation details that functions hide from one
another

 2006 Pearson Education, Inc. All rights reserved.


58

6.10 Scope Rules (Cont.)


• Block scope
– Identifiers declared inside a block have block scope
• Block scope begins at the identifier’s declaration
• Block scope ends at the terminating right brace (}) of the block in
which the identifier is declared
– Local variables and function parameters have block scope
• The function body is their block
– Any block can contain variable declarations
– Identifiers in an outer block can be “hidden” when a nested
block has a local identifier with the same name
– Local variables declared static still have block scope, even
though they exist from the time the program begins execution
• Storage duration does not affect the scope of an identifier

 2006 Pearson Education, Inc. All rights reserved.


59

6.10 Scope Rules (Cont.)


• Function-prototype scope
– Only identifiers used in the parameter list of a function
prototype have function-prototype scope
– Parameter names appearing in a function prototype are
ignored by the compiler
• Identifiers used in a function prototype can be reused
elsewhere in the program without ambiguity
• However, in a single prototype, a particular identifier can be
used only once

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 6.12: fig06_12.cpp
60
2
3
// A scoping example.
#include <iostream>
Outline
4 using std::cout;
5 using std::endl;
6
fig06_12.cpp
7 void useLocal( void ); // function prototype
8 void useStaticLocal( void ); // function prototype
9 void useGlobal( void ); // function prototype
(1 of 4)
10
11 int x = 1; // global variable
12 Declaring a global variable outside
13 int main() any class or function definition
14 {
15 int x = 5; // local variable to main
16
17 cout << "local x in main's outer scope is " Local variable
<< x << endl; x that hides global variable x
18
19 { // start new scope
20 int x = 7; // hides x in outer scope
21
22
Local variable x in a block that
cout << "local x in main's inner scope is " << x << endl;
23 } // end new scope hides local variablex in outer scope
24
25 cout << "local x in main's outer scope is " << x << endl;

 2006 Pearson Education,


Inc. All rights reserved.
26
61
27 useLocal(); // useLocal has local x
Outline
28 useStaticLocal(); // useStaticLocal has static local x
29 useGlobal(); // useGlobal uses global x
30 useLocal(); // useLocal reinitializes its local x
31 useStaticLocal(); // static local x retains its prior value fig06_12.cpp
32 useGlobal(); // global x also retains its value
33 (2 of 4)
34 cout << "\nlocal x in main is " << x << endl;
35 return 0; // indicates successful termination
36 } // end main
37
38 // useLocal reinitializes local variable x during each call
39 void useLocal( void )
Local variable that gets recreated and
40 {
reinitialized each time useLocal is called
41 int x = 25; // initialized each time useLocal is called
42
43 cout << "\nlocal x is " << x << " on entering useLocal" << endl;
44 x++;
45 cout << "local x is " << x << " on exiting useLocal" << endl;
46 } // end function useLocal

 2006 Pearson Education,


Inc. All rights reserved.
47
62
48 // useStaticLocal initializes static local variable x only the
Outline
49 // first time the function is called; value of x is saved
50 // between calls to this function
51 void useStaticLocal( void ) static local variable that gets initialized only once
52 { fig06_12.cpp
53 static int x = 50; // initialized first time useStaticLocal is called
54 (3 of 4)
55 cout << "\nlocal static x is " << x << " on entering useStaticLocal"
56 << endl;
57 x++;
58 cout << "local static x is " << x << " on exiting useStaticLocal"
59 << endl;
60 } // end function useStaticLocal
61
62 // useGlobal modifies global variable x during each call Statement refers to global variable x
63 void useGlobal( void ) because no local variable named x exists
64 {
65 cout << "\nglobal x is " << x << " on entering useGlobal" << endl;
66 x *= 10;
67 cout << "global x is " << x << " on exiting useGlobal" << endl;
68 } // end function useGlobal

 2006 Pearson Education,


Inc. All rights reserved.
local x in main's outer scope is 5 63
local x in main's inner scope is 7 Outline
local x in main's outer scope is 5

local x is 25 on entering useLocal


local x is 26 on exiting useLocal
fig06_12.cpp
local static x is 50 on entering useStaticLocal
local static x is 51 on exiting useStaticLocal
(4 of 4)
global x is 1 on entering useGlobal
global x is 10 on exiting useGlobal

local x is 25 on entering useLocal


local x is 26 on exiting useLocal

local static x is 51 on entering useStaticLocal


local static x is 52 on exiting useStaticLocal

global x is 10 on entering useGlobal


global x is 100 on exiting useGlobal

local x in main is 5

 2006 Pearson Education,


Inc. All rights reserved.
64
6.11 Function Call Stack and Activation
Records
• Data structure: collection of related data items
• Stack data structure
– Analogous to a pile of dishes
– When a dish is placed on the pile, it is normally placed at
the top
• Referred to as pushing the dish onto the stack
– Similarly, when a dish is removed from the pile, it is
normally removed from the top
• Referred to as popping the dish off the stack
– A last-in, first-out (LIFO) data structure
• The last item pushed (inserted) on the stack is the first item
popped (removed) from the stack

 2006 Pearson Education, Inc. All rights reserved.


65
6.11 Function Call Stack and Activation
Records (Cont.)
• Function Call Stack
– Sometimes called the program execution stack
– Supports the function call/return mechanism
• Each time a function calls another function, a stack frame
(also known as an activation record) is pushed onto the stack
– Maintains the return address that the called function
needs to return to the calling function
– Contains automatic variables—parameters and any
local variables the function declares

 2006 Pearson Education, Inc. All rights reserved.


66
6.11 Function Call Stack and Activation
Records (Cont.)
• Function Call Stack (Cont.)
– When the called function returns
• Stack frame for the function call is popped
• Control transfers to the return address in the popped stack frame
– If a function makes a call to another function
• Stack frame for the new function call is simply pushed onto the call
stack
• Return address required by the newly called function to return to its
caller is now located at the top of the stack.
• Stack overflow
– Error that occurs when more function calls occur than can have
their activation records stored on the function call stack (due to
memory limitations)

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 6.13: fig06_13.cpp
67
2
3
// square function used to demonstrate the function
// call stack and activation records.
Outline
4 #include <iostream>
5 using std::cin;
6 using std::cout;
fig06_13.cpp
7 using std::endl;
8
9 int square( int ); // prototype for function square
(1 of 1)
10
11 int main() Calling function square
12 {
13 int a = 10; // value to square (local automatic variable in main)
14
15 cout << a << " squared: " << square( a ) << endl; // display a squared
16 return 0; // indicate successful termination
17 } // end main
18
19 // returns the square of an integer
20 int square( int x ) // x is a local variable
21 {
22 return x * x; // calculate square and return result
23 } // end function square

10 squared: 100

 2006 Pearson Education,


Inc. All rights reserved.
68

Operating system calls main, pushing


an activation record onto the stack

Fig. 6.14 | Function call stack after the operating system invokes main to execute the
application.

 2006 Pearson Education, Inc. All rights reserved.


69

main calls function square, pushing another


stack frame onto the function call stack

Fig. 6.15 | Function call stack after main invokes function square to perform the
calculation.

 2006 Pearson Education, Inc. All rights reserved.


70

Program control returns to main and


square’s stack frame is popped off

Fig. 6.16 | Function call stack after function square returns to main.

 2006 Pearson Education, Inc. All rights reserved.


71
6.12 Functions with Empty Parameter
Lists
• Empty parameter list
– Specified by writing either void or nothing at all in
parentheses
– For example,
void print();
specifies that function print does not take arguments and
does not return a value

 2006 Pearson Education, Inc. All rights reserved.


72

Portability Tip 6.2

The meaning of an empty function parameter list


in C++ is dramatically different than in C. In C, it
means all argument checking is disabled (i.e., the
function call can pass any arguments it wants). In
C++, it means that the function explicitly takes no
arguments. Thus, C programs using this feature
might cause compilation errors when compiled in
C++.

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 6.17: fig06_17.cpp
73
2
3
// Functions that take no arguments.
#include <iostream>
Outline
Specify an empty parameter list by
4 using std::cout; putting nothing in the parentheses
5 using std::endl;
6
fig06_17.cpp
7 void function1(); // function that takes no arguments
8 void function2( void ); // function that takes no arguments
9
(1 of 2)
10 int main()
11 {
Specify an empty parameter list by
12 function1(); // call function1 with no arguments putting void in the parentheses
13 function2(); // call function2 with no arguments
14 return 0; // indicates successful termination
15 } // end main
16
17 // function1 uses an empty parameter list to specify that
18 // the function receives no arguments
19 void function1()
20 {
21 cout << "function1 takes no arguments" << endl;
22 } // end function1

 2006 Pearson Education,


Inc. All rights reserved.
23
74
24
25
// function2 uses a void parameter list to specify that
// the function receives no arguments
Outline
26 void function2( void )
27 {
28 cout << "function2 also takes no arguments" << endl;
fig06_17.cpp
29 } // end function2

function1 takes no arguments (2 of 2)


function2 also takes no arguments

 2006 Pearson Education,


Inc. All rights reserved.
75

6.13 Inline Functions


• Inline functions
– Reduce function call overhead—especially for small
functions
– Qualifier inline before a function’s return type in the
function definition
• “Advises” the compiler to generate a copy of the function’s
code in place (when appropriate) to avoid a function call
– Trade-off of inline functions
• Multiple copies of the function code are inserted in the
program (often making the program larger)
– The compiler can ignore the inline qualifier and typically
does so for all but the smallest functions

 2006 Pearson Education, Inc. All rights reserved.


76

Performance Tip 6.4

Using inline functions can reduce execution


time but may increase program size.

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 6.18: fig06_18.cpp
77
2
3
// Using an inline function to calculate the volume of a cube.
#include <iostream>
Outline
4 using std::cout;
5 using std::cin;
6 using std::endl;
fig06_18.cpp
7
8 // Definition of inline function cube. Definition of function appears
9 // before function is called, so a function prototype is not required.
(1 of 1)
10 // First line of function definition acts as the prototype.
11 inline double cube( const double side )
Complete function definition so the
12 {
inline qualifier compiler knows how to expand a cube
13 return side * side * side; // calculate cube
14 } // end function cube
function call into its inlined code.
15
16 int main()
17 {
18 double sideValue; // stores value entered by user
19 cout << "Enter the side length of your cube: ";
20 cin >> sideValue; // read value from user
21
22 // calculate cube of sideValue and display result
cube function call that could be inlined
23 cout << "Volume of cube with side "
24 << sideValue << " is " << cube( sideValue ) << endl;
25 return 0; // indicates successful termination
26 } // end main

Enter the side length of your cube: 3.5


Volume of cube with side 3.5 is 42.875

 2006 Pearson Education,


Inc. All rights reserved.

You might also like