05 Functions
05 Functions
Functions
Outline
Introduction
Program Components in C++
Functions
Function Definitions
Function Prototypes
Header Files
Random Number Generation
Example: A Game of Chance and Introducing enum
Scope Rules
Functions with Empty Parameter Lists
Inline Functions
Default Arguments
Unary Scope Resolution Operator
Function Overloading
Function Templates
Introduction
Functions
• Functions
– Modularize a program
– Software reusability
• Call function multiple times
• Local variables
– Known only in the function in which they are defined
– All variables declared in function definitions are local
variables
• Parameters
– Local variables passed to function when called
– Provide outside information
Function Definitions
• Function prototype
– Tells compiler argument type and return type of function
– int square( int );
• Function takes an int and returns an int
– Explained in more detail later
• Calling/invoking a function
– square(x);
– Parentheses an operator used to call function
• Pass argument x
• Function gets its own copy of arguments
– After finished, passes back result
Function Definitions
Function Definitions
• Example function
int square( int y )
{
return y * y;
}
• return keyword
– Returns data, and control goes to function’s caller
• If no data to return, use return;
– Function ends when reaches right brace
• Control goes to caller
• Functions cannot be defined inside other functions
• Next: program examples
2003 Prentice Hall, Inc. All rights reserved.
10
1 // Fig. 3.3: fig03_03.cpp
2 // Creating and using a programmer-defined function.
Outline
3 #include <iostream>
4 Function prototype: specifies fig03_03.cpp
5 using std::cout; data types of arguments and
6 using std::endl; (1 of 2)
return values. square
7
8 int square( int );
expects and int, and returns
// function prototype
9 an int.
10 int main()
11 {
12 Parentheses () cause function
// loop 10 times and calculate and output
13 // square of x each time to be called. When done, it
14 for ( int x = 1; x <= 10; x++ ) returns the result.
15 cout << square( x ) << " "; // function call
16
17 cout << endl;
18
19 return 0; // indicates successful termination
20
21 } // end main
22
Function Prototypes
Function Prototypes
• Function signature
– Part of prototype with name and parameters
• double maximum( double, double, double );
Function Prototypes
Da ta typ e s
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 (false becomes 0, true becomes 1)
Fig . 3.5 Pro m o tio n h ie ra rc h y fo r b u ilt-in d a ta typ e s.
Header Files
• Next
– Program to show distribution of rand()
– Simulate 6000 rolls of a die
– Print number of 1’s, 2’s, 3’s, etc. rolled
– Should be roughly 1000 of each
Enter seed: 67
6 1 4 6 2
1 6 1 6 4
• Enumeration
– Set of integers with identifiers
enum typeName {constant1, constant2…};
– Constants start at 0 (default), incremented by 1
– Constants need unique names
– Cannot assign integer to enumeration variable
• Must use a previously defined enumeration type
• Example
enum Status {CONTINUE, WON, LOST};
Status enumVar;
enumVar = WON; // cannot do enumVar = 1
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
Scope Rules
• Scope
– Portion of program where identifier can be used
• File scope
– Defined outside a function, known in all functions
– Global variables, function definitions and prototypes
• Function scope
– Can only be referenced inside defining function
– Only labels, e.g., identifiers with a colon (case:)
Scope Rules
• Block scope
– Begins at declaration, ends at right brace }
• Can only be referenced in this range
– Local variables, function parameters
– static variables still have block scope
• Storage class separate from scope
• Function-prototype scope
– Parameter list of prototype
– Names in prototype optional
• Compiler ignores
– In a single prototype, name can be used once
41
27
28 cout << "local x in main's outer scope is " << x << endl;
29
30 useLocal(); // useLocal has local x
31 useStaticLocal(); // useStaticLocal has static local x
fig03_12.cpp
32 useGlobal(); // useGlobal uses global x (2 of 5)
33 useLocal(); // useLocal reinitializes its local x
34 useStaticLocal(); // static local x retains its prior value
35 useGlobal(); // global x also retains its value
36
37 cout << "\nlocal x in main is " << x << endl;
38
39 return 0; // indicates successful termination
40
41 } // end main 2003 Prentice Hall, Inc.
42 All rights reserved.
42
Outline
fig03_12.cpp
(3 of 5)
43
56 // useStaticLocal initializes static local variable x only the
57 // first time the function is called; value of x is saved
58 // between calls to this function
59 void useStaticLocal( void )
60 {
fig03_12.cpp
61 // initialized only first time useStaticLocal is called (4 of 5)
62 static int x = 50;
63
64 cout << endl << "local static x is " << x
65 << " on entering useStaticLocal" << endl;
66 ++x;
67 cout << "local static x is " << xStatic local variable of
68 << function;
" on exiting useStaticLocal" it is initialized
<< endl; only
69 once, and retains its value
70 } // end function useStaticLocal
between function calls. 2003 Prentice Hall, Inc.
71
All rights reserved.
44
72 // useGlobal modifies global variable x during each call
73 void useGlobal( void )
Outline
74 {
75 cout << endl << "global x is " << x This function does not declarefig03_12.cpp
76 << " on entering useGlobal" << endl; any variables. It uses the
77 x *= 10; (5 of 5)
global x declared in the
78 cout << "global x is " << x
79 << " on exiting useGlobal" << endl;
beginning of the program. fig03_12.cpp
80 output (1 of 2)
81 } // end function useGlobal
local x in main is 5
Inline Functions
• Inline functions
– Keyword inline before function
– Asks the compiler to copy code into program instead of
making function call
• Reduce function-call overhead
• Compiler can ignore inline
– Good for small, often-used functions
• Example
inline double cube( const double s )
{ return s * s * s; }
– const tells compiler that function does not modify s
• Discussed in chapters 6-7
Default Arguments
fig03_24.cpp
Microsoft Visual C++ compiler output: (2 of 2)
Local float value of PI = 3.1415927410125732
Global double value of PI = 3.14159265358979
fig03_24.cpp
output (1 of 1)
Function Overloading
• Function overloading
– Functions with same name and different parameters
– Should perform similar tasks
• I.e., function to square ints and function to square floats
int square( int x) {return x * x;}
float square(float x) { return x * x; }
• Overloaded functions distinguished by signature
– Based on name and parameter types (order matters)
– Name mangling
• Encodes function identifier with parameters
– Type-safe linkage
• Ensures proper overloaded function called
Function Templates
Function Templates
• Example
template < class T > // or template< typename T >
T square( T value1 )
{
return value1 * value1;
}
– T is a formal type, used as parameter type
• Above function returns variable of same type as parameter
– In function call, T replaced by real type
• If int, all T's become ints
int x;
int y = square(x);