Sei sulla pagina 1di 73

1

Chapter 3 - Functions

Outline
3.1 Introduction
3.2 Program Components in C++
3.3 Math Library Functions
3.4 Functions
3.5 Function Definitions
3.6 Function Prototypes
3.7 Header Files
3.8 Random Number Generation
3.9 Example: A Game of Chance and Introducing enum
3.10 Storage Classes
3.11 Scope Rules
3.12 Recursion
3.13 Example Using Recursion: The Fibonacci Series
3.14 Recursion vs. Iteration
3.15 Functions with Empty Parameter Lists

2000 Prentice Hall, Inc. All rights reserved.

Chapter 3 - Functions

Outline
3.16 Inline Functions
3.17 References and Reference Parameters
3.18 Default Arguments
3.19 Unary Scope Resolution Operator
3.20Function Overloading
3.21Function Templates

2000 Prentice Hall, Inc. All rights reserved.

3.1

Introduction

Divide and conquer


Construct a program from smaller pieces or
components

Each piece more manageable than the original program

2000 Prentice Hall, Inc. All rights reserved.

3.2

Program Components in C++

Programs written by
combining new functions with prepackaged
functions in the C++ standard library.
The standard library provides a rich collection
of functions.

Input/output (getline, read etc.)


Common mathematical calculations (pow, sqrt, exp,
etc.)
String manipulations(strcpy, strcat, etc.
Many more

2000 Prentice Hall, Inc. All rights reserved.

3.2

Program Components in C++

Functions are invoked by a function call

A function call specifies the function name and


provides information (as arguments) that the called
function needs
Boss to worker analogy:
A boss (the calling function or caller) asks a worker
(the called function) to perform a task and return
(i.e., report back) the results when the task is done.

2000 Prentice Hall, Inc. All rights reserved.

3.2

Program Components in C++

Function definitions

Only written once


These statements are hidden from other functions.
Boss to worker analogy:
The boss does not know how the worker gets the job
done; he just wants it done

2000 Prentice Hall, Inc. All rights reserved.

3.3

Math Library Functions

Math library functions


Allow the programmer to perform common mathematical
calculations
Are used by including the header file<math.h>

Functions called by writing


functionName (argument)

Example
cout << sqrt( 900.0 );

Calls the sqrt (square root) function. The preceding


statement would print 30
The sqrt function takes an argument of type double and
returns a result of type double, as do all functions in the
math library
2000 Prentice Hall, Inc. All rights reserved.

3.3

Math Library Functions

Function arguments can be


Constants
sqrt( 4 );

Variables
sqrt( x );

Expressions

sqrt( sqrt( x ) ) ;
sqrt( 3 - 6x );

2000 Prentice Hall, Inc. All rights reserved.

3.4

Functions

Functions
Allow the programmer to modularize a program

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 when the function is called that


provide the function with outside information

2000 Prentice Hall, Inc. All rights reserved.

10

3.5

Function Definitions

Create customized functions to


Take in data
Perform operations
Return the result

Formatforfunctiondefinition:
returnvaluetypefunctionname( parameterlist )
{
declarationsandstatements
}

Example:

int square( int y)


{
return y * y;
}
2000 Prentice Hall, Inc. All rights reserved.

11

1 // Fig. 3.3: fig03_03.cpp


2 // Creating and using a programmer-defined
function
3 #include <iostream.h>
4

Notice how parameters and


return value are declared in
thefunction
function prototype
//
prototype

7
8 int square( int );
9
10 int main()
11 {
12
for ( int x = 1; x <= 10; x++ )
13
cout << square( x ) << " ";
14
15
cout << endl;
The function square is
16
return 0;
for x = 1, 2, 10
17 }
18
19 // Function definition
20 int square( int y )
Function definition
21 {
22
return y * y;
23 }
1

16

25

36

49

64

81

100

2000 Prentice Hall, Inc. All rights reserved.

Outline

1. Function prototype
2. Loop
3. Function definition

called

Program Output

12

3.6

Function Prototypes

Function prototype
Function name
Parameters
Information, the function takes in

Return type

Type of information the function passes back to caller (default int)


void signifies the function returns nothing
Note that it is enough to mention
Only
neededofifthe
function
just
the data-type
input definition comes after the function
parameters
in the
function
call in the
program
However, it is ok to mention the
prototype
Example:
variable names as well
int maximum( int, int, int );

Takes in 3 ints
Returns an int
2000 Prentice Hall, Inc. All rights reserved.

int maximum( int x, int y, int z);

13

1 // Fig. 3.4: fig03_04.cpp


2 // Finding the maximum of three integers
3 #include <iostream.h>
4 int maximum( int, int, int );
prototype
5

// function

6 int main()
7 {
8

int a, b, c;

9
10

cout << "Enter three integers: ";

11

cin >> a >> b >> c;

12
13

// a, b and c below are arguments to

14

// the maximum function call

15
cout << "Maximum is: " << maximum( a, b, c ) <<
endl;
16
17
return 0;
18 }

2000 Prentice Hall, Inc. All rights reserved.

Outline

1. Function prototype
(3 parameters)
2. Input values
2.1 Call function

19 // Function maximum definition


20 // x, y and z below are parameters to

14

Outline

21 // the maximum function definition


3. Function definition
22 int maximum( int x, int y, int z )
23 {
Initially, max is equal to x
24
int max = x;
25
26
if ( y > max )
If y is greater than max,
27
max = y;
y becomes the new max now
28
29
if ( z > max )
Finally, if z is greater than max,
30
max = z;
z becomes the new max
31
32
return max;
33 }
Enter three integers: 22 85 17
Maximum is: 85
Enter three integers: 92 35 14
Maximum is: 92
Enter three integers: 45 19 98
Maximum is: 98

2000 Prentice Hall, Inc. All rights reserved.

Program Output

15

3.7

Header Files

Header files
Contain function prototypes for library functions
Load with #include <filename.h>
Example:
<stdlib.h> , <math.h>, etc.

Custom header files


Defined by the programmer
Save as filename.h
Loaded into program using

#include "filename.h"

2000 Prentice Hall, Inc. All rights reserved.

16

3.8

Random Number Generation

rand function
i = rand();

Generates a pseudorandom number between 0 and RAND_MAX


(usually 32767)
A pseudorandom number is a preset sequence of "random" numbers
The same sequence is generated upon every program execution

Load <stdlib.h>
srand function
Jumps to a seeded location in a "random" sequence
srand( seed );
srand( time( 0 ) ); //must include <time.h>

time( 0 )
The time at which the program was compiled

Changes the seed every time the program is compiled, thereby


allowing rand to generate random numbers
2000 Prentice Hall, Inc. All rights reserved.

17

3.8

Random Number Generation

Scaling
Reduces random number to a certain range
Modulus ( % ) operator
Reduces number between 0 and RAND_MAX to a number
between 0 and the scaling factor

Example

i = rand() % 6 + 1;
Generates a number between 1 and 6

2000 Prentice Hall, Inc. All rights reserved.

1
2
3
%
4

// Fig. 3.7: fig03_07.cpp


// Shifted, scaled integers produced by 1 + rand()
6#include <iostream.h>

8 #include <iomanip.h>
9
10 #include <cstdlib>

Outline

1. Define loop
2. Output random
number

11

18

Notice rand() % 6 .
This returns a number between 0 and 5 (scaling).

12 int main()
13 {
Add 1 to get a number between 1 and 6.
14
for ( int i = 1; i <= 20; i++ ) {
15
16
17

cout << setw( 10 ) << ( 1 + rand() % 6 );


if ( i % 5 == 0 )

18
19
20
21
22 }

cout << endl;

return 0;

5
2
5
5

5
4
3
1

Executing the program again gives


the same "random" dice rolls.
3
2
2
4

2000 Prentice Hall, Inc. All rights reserved.

5
5
2
6

5
5
1
4

Program Output

19

1 // Randomizing die-rolling program


2 #include <iostream.h>
3 #include <iomanip.h>

1. Initialize seed

4 #include <cstdlib.h>
5 int main()
6 {
7
unsigned seed;
8
9
10
11
12
13
14
15
16

2. Input value for seed

cout << "Enter seed: ";


cin >> seed;
srand( seed );

Now, every time the program is


executed, srand is called with a 2.1 Use srand to
new seed entered by the user
change random
sequence

for ( int i = 1; i <= 10; i++ ) {


cout << setw( 10 ) << 1 + rand() % 6;

2.2 Define Loop

if ( i % 5 == 0 )
cout << endl;

17

18
19 }

return 0;

Outline

3. Generate and
output random
numbers

Enter seed: 67
1
5

6
6

5
3

1
1

4
2

Enter seed: 432


4
2

2
5

6
1

4
4

3
4

1
1

4
2

Enter seed: 67
1
6
5
5
6
3
2000 Prentice Hall, Inc. All rights reserved.

Program Output

Notice how the die rolls


change with the seed.

/* Fig. 5.8: fig05_08.c

Outline

Roll a six-sided die 6000 times */

#include <iostream.h>

#include <stdlib.h>

fig05_08.c
(Part 1 of 3)

5
6

/* function main begins program execution */

int main()

int frequency1 = 0; /* rolled 1 counter*/

10

int frequency2 = 0; /* rolled 2 counter */

11

int frequency3 = 0; /* rolled 3 counter */

12

int frequency4 = 0; /* rolled 4 counter */

13

int frequency5 = 0; /* rolled 5 counter */

14

int frequency6 = 0; /* rolled 6 coun


ter */

A C/C++ program which simulates the


rolling of die 6000 times and calculates
and displays the number of times each
number (1 6) is encountered

15
16

int roll; /* roll counter */

17

int face; /* represents one roll of the die, value 1 to 6 */

18
19

/* loop 6000 times and summarize results */

20

for ( roll = 1; roll <= 6000; roll++ ) {

21

face = 1 + rand( ) % 6; /* random number from 1 to 6 */

22

2000 Prentice Hall, Inc. All rights reserved.

23

/* determine face value and increment appropriate counter */

24

switch ( face ) {

Outline

25
26
27

case 1:

/* rolled 1 */

28

++frequency1;
break ;

29
30
31

case 2:

/* rolled 2 */

32

++frequency2;
break ;

33
34
35

case 3:

/* rolled 3 */

36

++frequency3;
break ;

37
38
39

case 4:

/* rolled 4 */

40

++frequency4;
break ;

41
42
43

case 5:

/* rolled 5 */

44

++frequency5;
break ;

45

2000 Prentice Hall, Inc. All rights reserved.

fig05_08.c
(Part 2 of 3)

45
46
47
48
49
50
51
52
53

case 6 :
/* rolled 6 */
++frequency6;
break;
} /* end switch */
} /* end for */

Outline
fig05_08.c
(Part 3 of 3)

/* display results in tabular format */


cout
cout
cout
cout
cout
cout
cout

<<
<<
<<
<<
<<
<<
<<

\nFace<< setw( 13

1<< setw( 13 )

2<< setw( 13 )

3<< setw( 13 )

4<< setw( 13 )

5<< setw( 13 )

6<< setw( 13 )

) << Frequency\n;
<< frequency1<<\n;
<< frequency2<<\n;
<< frequency3<<\n;
<< frequency4<<\n;
<< frequency5<<\n;
<< frequency6<<\n;

61
62
return 0 ; /* indicates successful termination */
63
64 } /* end main */

Program
Output
2000 Prentice Hall, Inc. All rights reserved.

Outline

Face
1
2
3
4
5
6

Frequency
1003
1017
983
994
1004
999

2000 Prentice Hall, Inc. All rights reserved.

24

3.9 Introducing enum


Enumeration - set of integers with identifiers
enum typeName {constant1, constant2};

Constants start at 0 (default), incremented by 1


Unique constant names
Example:
enum Status {CONTINUE, WON, LOST};

Create an enumeration variable of type typeName


Variable is constant, its value may not be reassigned

Status enumVar;
enumVar = WON;
enumVar = 1;
cout<<enumVar;

2000 Prentice Hall, Inc. All rights reserved.

//
//
//
//

create variable
set equal to WON
ERROR
What will print?

25

Introducing enum(II)
Enumeration constants can have values pre-set

enum Months { JAN = 1, FEB, MAR, APR, MAY,


JUN, JUL, AUG, SEP, OCT, NOV, DEC};
Starts at 1, increments by 1

2000 Prentice Hall, Inc. All rights reserved.

3.10 Storage Classes

26

What are the attributes of a variable?


type, name, size, and value
int var = 5;

What is an identifier?
An identifier is used for any variable, function, data definition etc.

Each identifier in a program has other attributes


Storage class
Determines the period during which the that identifier exists in memory
exist briefly,
repetitively created/destroyed,
exist during entire program execution

Scope
Where object is referenced in program

Linkage
Where an identifier is known (i.e, which source file?)

C++ provides five storage class specifiers

auto
register
extern
mutable
static

2000 Prentice Hall, Inc. All rights reserved.

27

3.10 Storage Classes


auto Storage Class: The auto storage class is the default storage class for all local
variables. Object created and destroyed within its block.
{
int mount;
auto int month;
}

register Storage Class: The register storage class is used to define local variables that
require quick access such as counters.
{
register int miles;
}

static Storage Class: The static storage class instructs the compiler to keep a local

variable in existence during the life-time of the program instead of creating and destroying
it each time it comes into and goes out of scope.

void fun() {
static int i = 10;
i++; cout << i; }
int main() {
fun(); // Output = 11
fun(); // Output = 12
fun(); // Output = 13 }
2000 Prentice Hall, Inc. All rights reserved.

28

3.10 Storage Classes


extern Storage Class: When you have multiple files and you define a

global variable or function, which will be used in other files also, then extern will
be used in another file to give reference of defined variable or function.

mutable Storage Class: Mutable is applicable for class and is

used to modify a constant member of a class.

2000 Prentice Hall, Inc. All rights reserved.

29

3.11 Identifier Scope Rules


File scope
Defined outside a function, known in all functions
Examples include, global variables, function definitions and
functions prototypes

Function scope
Can only be referenced inside a function body

Block scope
Declared inside a block. Begins at declaration, ends at }
Variables, function parameters (local variables of function)
Outer blocks hidden from inner blocks if same variable name

Function prototype scope

Identifiers in parameter list


Names in function prototype optional, and can be used anywhere
2000 Prentice Hall, Inc. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

30

// Fig. 3.12: fig03_12.cpp


// A scoping example
#include <iostream.h>

Outline

1. Function prototypes
void a( void );
void b( void );
void c( void );

// function prototype
// function prototype
// function prototype

x is different inside and outside


variable
the block.

int x = 1;

// global

int main()
{
int x = 5;

// local variable to main

cout << "local x in outer scope of main is " << x << endl;
{

// start new scope

1.1 Initialize global


variable
1.2 Initialize local
variable
1.3 Initialize local
variable in block
2. Call functions

int x = 7;

cout << "local x in inner scope of main is " << x << endl;
// end new scope

3. Output results

cout << "local x in outer scope of main is " << x << endl;
a();
// a has automatic local x
b();
// b has static locallocal
x
x in outer scope of main is 5
c();
// c uses global x
local x in inner scope of main is 7
a();
// a reinitializes automatic
local
x scope of main is 5
local x in
outer
b();
// static local x retains its previous value
c();
// global x also retains its value
2000 Prentice Hall, Inc. All rights reserved.

35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

31

cout << "local x in main is " << x << endl;


return 0;

Local automatic variables are


created and destroyed each 3.1 Define Functions
time a is called.

}
void a( void )
{
int x = 25;
cout <<
<<
++x;
cout <<
<<

Outline

// initialized each time a is called

endl << "local x in a is " << x


" after entering a" << endl;

local x in a is 25 after entering a


local x in a is 26 before exiting a

"local x in a is " << x


" before exiting a" << endl;

}
void b( void )
{
static int x = 50;
cout <<
<<
++x;
cout <<
<<
}

Local static variables are not

// Static initialization only


destroyed when the function
// first time b is called.
ends.
endl << "local static x is " << x
" on entering b" << endl;
local static x is 50 on entering b
"local static x is " << x
local static x is 51 on exiting b
" on exiting b" << endl;

Global variables are always


accessible. Function c references
the global x.

void c( void )
{
cout << endl << "global x is " << x
<< " on entering c" << endl;
x *= 10;
cout << "global x is " << x << " on exiting c" << endl;
} 2000 Prentice Hall, Inc. All rights reserved.

global x is 1 on entering c
global x is 10 on exiting c

32
local x in outer scope of main is 5
local x in inner scope of main is 7
local x in outer scope of main is 5
local x in a is 25 after entering a
local x in a is 26 before exiting a
local static x is 50 on entering b
local static x is 51 on exiting b
global x is 1 on entering c
global x is 10 on exiting c
local x in a is 25 after entering a
local x in a is 26 before exiting a
local static x is 51 on entering b
local static x is 52 on exiting b
global x is 10 on entering c
global x is 100 on exiting c
local x in main is 5

2000 Prentice Hall, Inc. All rights reserved.

Outline

Program Output

Function Scope Examples

#include<iostream.h>
#include<conio.h>
int x = 5;
void fun1();
void fun2();
void fun3(int x, int y);
void main(){
clrscr(); int x=10; int y = -1;
cout<<"\nmain( ): x: "<<x;
for (int i = 20; i <= 25; i++ ){
int x = i ;
cout<<"\nfor loop: x: "<<x;
}
cout<<"\nmain( ): x: "<<x;
fun1();
fun1(
cout<<"\nmain( ): x: "<<x;
fun2( );
fun2(
fun1( );
fun1(
fun2( );
fun2(
fun3(x,y);
cout<<"\n\nmain( ): x: "<<x;
cout<<"\n
y: "<<y;
getch();
}
2000 Prentice Hall, Inc. All rights reserved.

main( ): x: 10
for loop: x: 20
for loop: x: 21
for loop: x: 22
for loop: x: 23
for loop: x: 24
for loop: x: 25

): x: 20

main( ): x: 10
y: 6
main( ): x: 10

): x: 5
): x: 20
): x: 5

y: 9

main( ): x: 10
y: -1

Function Scope Examples


void fun1( ){
int x = 20;
static int y = 3;
y = y+3;
cout<<"\n\nfun1( ): x: "<<x;
cout<<"\n
y: "<<y;
}
void fun2( ){
cout<<"\nfun2(): x: "<<x;
}

void fun3( int x, int y ){


x = 100;
y = 200;
}

2000 Prentice Hall, Inc. All rights reserved.

35

3.12 Recursion
Recursive functions
Are functions that call themselves
Can only solve a base case
If not base case, the function breaks the problem into a
slightly smaller, slightly simpler, problem that resembles the
original problem and
Launches a new copy of itself to work on the smaller problem,
slowly converging towards the base case
Makes a call to itself inside the return statement

Eventually the base case gets solved and then that value
works its way back up to solve the whole problem

2000 Prentice Hall, Inc. All rights reserved.

36

3.12 Recursion
Example: factorial
n! = n * ( n 1 ) * ( n 2 ) * * 1

Recursive relationship ( n! = n * ( n 1 )! )
5! = 5 * 4!
4! = 4 * 3!

Base case (1! = 0! = 1)

2000 Prentice Hall, Inc. All rights reserved.

Recursion
void print(int n)
{
if (n<1) return;
cout<<n;
print(n-1);
}

What would be the output of print(5)?


2000 Prentice Hall, Inc. All rights reserved.

Recursion unrolled
What would be the output of print(5)?
print(5)
5 <1 ?
cout<<n;
5
print(4)
4 <1 ?
cout<<n;
4
print(3)
3 <1 ?
cout<<n; 3
print(2)
2<1 ?
cout<<n; 2
print(1)
1 <1 ?
cout<<n; 1
print(0)
0<1
return;

2000 Prentice Hall, Inc. All rights reserved.

Recursion
void print(int n)
{
if (n<1) return;
print(n-1);
cout<<n;
}

What would be the output of print(5)?


2000 Prentice Hall, Inc. All rights reserved.

Recursion unrolled
What would be the output of print(5)?
print(5)
5 <1 ?
print(4)
(4 <1) ?
print(3)
(3 <1) ?
print(2)
(2<1) ?
print(1)
(1 <1) ?
print(0)
(0 < 1) return
cout<<n; 1
cout<<n;
2
cout<<n; 3
cout<<n;
4
cout<<n; 5

2000 Prentice Hall, Inc. All rights reserved.

void print(int n){


if (n<1) return;
print(n-1);
cout<<n;
}

Recursion
void print(int n)
{
if (n<1) {}
else
cout<<n;
print(n-1);
}

What would be the output of print(5)?


2000 Prentice Hall, Inc. All rights reserved.

42

Example Using Recursion: Factorial


n! = n * ( n 1 ) * ( n 2 ) * * 1

Recursive relationship ( n! = n * ( n 1 )! )
5! = 5 * 4!
4! = 4 * 3!

Base case (1! = 0! = 1)

C++ code for factorial function

unsigned long factorial(unsigned long n )


{
if ( n <= 1) // base case
return 1;
else // recursive case
return n * factorial(n -1);
}

2000 Prentice Hall, Inc. All rights reserved.

43

Factorial: Non-recursive implementation


unsigned long factorial(unsigned long n )
{
for (int i = n-1; i >0; i--)

n = n*i;
return n;
}
int main(){
cout << factorial(5);
return 0;
}

2000 Prentice Hall, Inc. All rights reserved.

3.13 Example Using Recursion: The


Fibonacci Series

44

Fibonacci series: 0, 1, 1, 2, 3, 5, 8...


Each number sum of two previous ones
Example of a recursive formula:
fib(n) = fib(n-1) + fib(n-2)

C++ code for fibonacci function

long fibonacci( long n )


{
if ( n == 0 || n == 1 ) // base case
return n;
else
return fibonacci( n - 1 ) + fibonacci( n 2 );
}

2000 Prentice Hall, Inc. All rights reserved.

3.13 Example Using Recursion: The


Fibonacci Series
Diagram of Fibonnaci function
f(3)

return

return

f(1)

return1

2000 Prentice Hall, Inc. All rights reserved.

f(2)

f(0)

return0

f(1)

return1

45

3.13 Example Using Recursion: The


Fibonacci Series

f(3)

return

return

f(1)

return1

f(2)

f(0)

f(1)

return1

return0

Diagram of Fibonnaci function

2000 Prentice Hall, Inc. All rights reserved.

46

1 // Fig. 3.15: fig03_15.cpp


2 // Recursive fibonacci function
3 #include <iostream.h>

47

Outline

1. Function prototype
4 unsigned long fibonacci( unsigned long );
5 int main()
1.1 Initialize variables
6 {
7
unsigned long result, number;
2. Input an integer
8
2.1 Call function fibonacci
9
cout << "Enter an integer: ";
10
cin >> number;
2.2 Output results.
11
result = fibonacci( number );
12
cout << "Fibonacci(" << number << ") = " << result
3. Define fibonacci
13
return 0;
<< endl;
recursively
14 }
15
16 // Recursive definition of function fibonacci
Only the base cases return values. All
17 unsigned long fibonacci( unsigned long other
n ) cases call the fibonacci
18 {
function again.
19
if ( n == 0 || n == 1 ) // base case
20
return n;
21
else
// recursive case
22
return fibonacci( n - 1 ) + fibonacci( n - 2 );
23 }

2000 Prentice Hall, Inc. All rights reserved.

Enter an integer: 0
Fibonacci(0) = 0
Enter an integer: 1
Fibonacci(1) = 1
Enter an integer: 2
Fibonacci(2) = 1
Enter an integer: 3
Fibonacci(3) = 2
Enter an integer: 4
Fibonacci(4) = 3
Enter an integer: 5
Fibonacci(5) = 5
Enter an integer: 10
Fibonacci(10) = 55
Enter an integer: 6
Fibonacci(6) = 8
Enter an integer: 20
Fibonacci(20) = 6765
Enter an integer: 30
Fibonacci(30) = 832040
Enter an integer: 35
Fibonacci(35) = 9227465

2000 Prentice Hall, Inc. All rights reserved.

48

Outline

Program Output

49

3.14 Recursion vs. Iteration


Repetition
Iteration: explicit loop
Recursion: repeated function calls

Termination
Iteration: loop condition fails
Recursion: base case recognized

Both can have infinite loops


Balance between performance (iteration) and good
software engineering (recursion)

2000 Prentice Hall, Inc. All rights reserved.

50

3.15 Functions with Empty Parameter Lists


Empty parameter lists
Either writing void or leaving a parameter list empty
indicates that the function takes no arguments
void print();
or
void print( void );

Function print takes no arguments and returns no value

2000 Prentice Hall, Inc. All rights reserved.

51

// Functions that take no arguments


#include <iostream.h>
void function1();
void function2( void );

Notice the two ways of


declaring no
arguments.

int main()
{
function1();
function2();
return 0;

Outline

1. Function prototypes
(take no
arguments)
2. Call the functions
3. Function definitions

}
void function1()
{
cout << "function1 takes no arguments" << endl;
}
void function2( void )
{
cout << "function2 also takes no arguments" << endl;

Program Output

}
function1 takes no arguments
function2 also takes no arguments

2000 Prentice Hall, Inc. All rights reserved.

52

3.16 Inline Functions

inline functions

Reduce function-call overhead


Asks the compiler to copy code into program instead
of using a function call
Compiler can ignore inline
Should be used with small, often-used functions

Example 1:
inline double cube( const double s )
{ return s * s * s; }

Example 2

inline int max(int a, int b){


return (a > b) ? a : b;
}
2000 Prentice Hall, Inc. All rights reserved.

53

3.17 References and Reference Parameters


Call by value
Copy of data passed to function
Changes to copy do not change original
Used to prevent unwanted side effects

Call by reference
Function can directly access data
Changes affect original

Reference parameter alias for argument


& is used to signify a reference
void change( int &variable )
{ variable += 3; }

Adds 3 to the variable inputted


int &y = x.

A change to y will now affect x as well


2000 Prentice Hall, Inc. All rights reserved.

Using a Reference Parameter


Is like giving someone the key
to your home

The key can be used by the


other person to change the
contents of your home!

2000 Prentice Hall, Inc. All rights reserved.

Main Program Memory


4000

25
age
If you pass a copy of age to a function, it is called
pass-by-value and the function will not be able
to change the contents of agein the calling
block; it is still 25 when you return

BUT, if you pass 4000, the address of age to a


function, it is called pass-by-reference and the
function will be able to change the contents of
age in the calling block; it could be 23 or 90 when
you return
2000 Prentice Hall, Inc. All rights reserved.

Additional Terms
Pass-by-reference
is also called . . .
pass-by-address, or
pass-by-location

Can you explain why?

2000 Prentice Hall, Inc. All rights reserved.

Pass-by-value
incoming
value of
argument

CALLING
BLOCK

2000 Prentice Hall, Inc. All rights reserved.

FUNCTION
CALLED

Pass-by-reference
incoming
original value of
argument
CALLING
BLOCK

FUNCTION
CALLED

outgoing
changed value of
argument

2000 Prentice Hall, Inc. All rights reserved.

OR,

Pass-by-reference
OR argument
has no value yet
when call occurs
CALLING
BLOCK

FUNCTION
CALLED

outgoing
new value of
argument

2000 Prentice Hall, Inc. All rights reserved.

// Comparing call-by-value and call-by-reference

60

Notice the use of the & operator

// with references.

Outline

#include <iostream.h>
int squareByValue( int );
void squareByReference( int & );

1. Function prototypes
1.1 Initialize variables

int main()
{
int x = 2, z = 4;
cout << "x = " << x << " before squareByValue\n"
<< "Value returned by squareByValue: "
<< squareByValue( x ) << endl
<< "x = " << x << " after squareByValue\n"<<endl;
cout << "z = " << z << " before squareByReference" <<
endl;

squareByReference( z );
cout << "z = " << z << " after squareByReference" <<

endl;

return 0;

int squareByValue( int a )


{

2.1 Call function and


print x
2.2 Print z
2.3 Call function and
print z
3. Function Definition of
squareByValue

return a *= a;

2. Print x

// caller's argument not modified

2000 Prentice Hall, Inc. All rights reserved.

61
void squareByReference( int &cRef )

Outline

cRef *= cRef;

// caller's argument modified

}
x = 2 before squareByValue
Value returned by squareByValue: 4
x = 2 after squareByValue
z = 4 before squareByReference
z = 16 after squareByReference

2000 Prentice Hall, Inc. All rights reserved.

3.1 Function Definition of


squareByReference
Program Output

Outline

Example of Pass-by-Reference

We want to find 2 real roots for a


quadratic equation with coefficients
a,b,c. Write a prototype for a void
function named GetRoots() with 5
parameters. The first 3 parameters
are type float. The last 2 are
reference parameters of type float.

2000 Prentice Hall, Inc. All rights reserved.

Outline

// Prototype
voidGetRoots(float,float,float,
float&,float&);
Now write the function definition using this information

This function uses 3 incoming values a, b, c from the


calling block. It calculates 2 outgoing values root1
and root2 for the calling block. They are the 2 real
roots of the quadratic equation with coefficients a, b,
c.

2000 Prentice Hall, Inc. All rights reserved.

Outline

Function Definition
voidGetRoots(floata,floatb,floatc,
float&root1,float&root2)
{
floattemp;
//Localvariable

temp=b*b4.0*a*c;
root1=(b+sqrt(temp))/(2.0*a);
root2=(bsqrt(temp))/(2.0*a);
return;
}

64
2000 Prentice Hall, Inc. All rights reserved.

65

3.18 Default Arguments

If function parameter omitted, gets default


value
Can be constants, global variables, or function calls
If not enough parameters specified, rightmost go to
their defaults

Set defaults in function prototype

int defaultFunction( int x = 1,


int y = 2, int z = 3 );

2000 Prentice Hall, Inc. All rights reserved.

// Fig. 3.23: fig03_23.cpp


// Using default arguments
#include <iostream.h>

66

Outline

int boxVolume( int length = 1, int width = 1, int height = 1 ); 1. Function prototype
int main()
{
cout<< "The default box volume is: " << boxVolume()
<< "\n\nThe volume of a box with length 10,\n"
<< "width 1 and height 1 is: " << boxVolume( 10 )
<< "\n\nThe volume of a box with length 10,\n"
<< "width 5 and height 1 is: " << boxVolume( 10, 5 )

2. Print default volume


2.1 Print volume with
one parameter
2.2 Print with 2
parameters

<< "\n\nThe volume of a box with length 10,\n"

<< "width 5 and height 2 is: " << boxVolume( 10, 5, 2 ) 2.3 Print with all
<< endl;

20

return 0;
}
// Calculate the volume of a box
int boxVolume( int length, int width, int height )
{
return length * width * height;

}
2000 Prentice Hall, Inc. All rights reserved.

parameters.

3. Function definition

67
The default box volume is: 1

Program Output

The volume of a box with length 10,


width 1 and height 1 is: 10
The volume of a box with length 10,
width 5 and height 1 is: 50
The volume of a box with length 10,
width 5 and height 2 is: 100

Notice how the rightmost


values are defaulted.

2000 Prentice Hall, Inc. All rights reserved.

Outline

68

3.20 Function Overloading


Function overloading
Having functions with same name and different parameters
Should perform similar tasks ( i.e., a function to square
ints, and function to square floats).
int square( int x) {return x * x;}
float square(float x) { return x * x; }

Program chooses function by signature


signature determined by function name and parameter types

Can have the same return types

2000 Prentice Hall, Inc. All rights reserved.

// Fig. 3.25: fig03_25.cpp

// Using overloaded functions

#include <iostream>

4
5

using std::cout;

using std::endl;

69

Functions have same name but


different parameters

7
8

int square( int x ) { return x * x; }

Outline

1. Define overloaded
function
2. Call function

9
10 double square( double y ) { return y * y; }
11
12 int main()
13 {
14

cout << "The square of integer 7 is " << square( 7 )

15

<< "\nThe square of double 7.5 is " << square( 7.5 )

16

<< endl;

17
18

return 0;

19 }

The square of integer 7 is 49


The square of double 7.5 is 56.25

2000 Prentice Hall, Inc. All rights reserved.

Program Output

70

3.19 Unary Scope Resolution Operator


Unary scope resolution operator (::)

Access global variables if a local variable has same name


not needed if names are different
instead of variable use ::variable

2000 Prentice Hall, Inc. All rights reserved.

71
// Fig. 3.24: fig03_24.cpp
// Using the unary scope resolution operator

Outline

1. Define variables

#include <iostream.h>

2. Print variables

#include <iomanip.h>

const double PI = 3.14159265358979;

Notice the use of ::

int main()
{
const float PI = static_cast< float >( ::PI );
cout << setprecision( 20 )
<< "

Local float value of PI = " << PI

<< "\nGlobal double value of PI = " << ::PI << endl;


return 0;
}

Local float value of PI = 3.141592741012573242


Global double value of PI = 3.141592653589790007

2000 Prentice Hall, Inc. All rights reserved.

Program Output

72

3.21 Function Templates


Function templates
Compact way to make overloaded functions
Keyword template
Keyword class or typename before every formal type
parameter (built in or user defined)
template < class T
// or template<
T square( T value1
{
return value1 *
}

>
typename T >
)
value1;

T replaced by type parameter in function call.


int x;
int y = square(x);
If int, all T's become ints
Can use float, double, long...

2000 Prentice Hall, Inc. All rights reserved.

// function template
#include <iostream.h>
template <class T>
T GetMax (T a, T b) {
T result;
result = (a>b)? a : b;
return (result);

}
int main () {
int i = 5, j = 6, k;
long l = 10, m = 5, n;
k = GetMax <int>(i , j);
n = GetMax <long>(l , m);
cout << k << endl;
cout << n << endl;
return
2000 Prentice
Hall, Inc. 0;
All }
rights reserved.

Potrebbero piacerti anche