chapter 8

10
Chapter 8 Functions Learning Objectives After studying this chapter a student should be able to: Explain what a function is. Explain the role of a function’s parameters. Explain the role of a function’s return value. Differentiate between function input/output and input/output via the console. Identify the parts of a function definition function header, body, return type, parameters, and name. Identify and author C/C++ language syntax to declare a function. List the order in which functions must be declared knowing only which function calls which. Author appropriately descriptive comments to document a function. Explain what it means for a parameter to be pass-by-value. Trace, by hand, the execution of a C/C++ program into and through a function call. Describe, in plain English, the behaviour of a computer program when a function call is performed. Identify and author C/C++ language syntax to declare a function with no parameters. Explain the role and behaviour of the return statement. Identify and author C/C++ language syntax to declare a procedure. Differentiate between situations in which a function should be declared instead of a proce- dure, and vice versa. Functionally decompose a problem, or algorithm, in a sensible manner. 8.1 Introduction A function is an encapsulation of an algorithm (we discussed encapsulation in Chapter 1). It is a way of referring, by name, to a set of instructions which accomplish a specific task. We distinguish between defining a function, and using a function. The definition does not cause the function to do anything; it’s just a set of instructions, a potential, waiting to happen. The function only gets set into action if it is called by some other part of the program. D.Neilson, M.Horsch, ”CMPT 111: Introduction to Computer Science and Programming” 59

Upload: frankynevin1

Post on 23-Oct-2015

21 views

Category:

Documents


3 download

DESCRIPTION

Computer Science Chapter 8

TRANSCRIPT

Chapter 8

Functions

Learning Objectives

After studying this chapter a student should be able to:

• Explain what a function is.• Explain the role of a function’s parameters.• Explain the role of a function’s return value.• Differentiate between function input/output and input/output via the console.• Identify the parts of a function definition function header, body, return type, parameters,

and name.• Identify and author C/C++ language syntax to declare a function.• List the order in which functions must be declared knowing only which function calls

which.• Author appropriately descriptive comments to document a function.• Explain what it means for a parameter to be pass-by-value.• Trace, by hand, the execution of a C/C++ program into and through a function call.• Describe, in plain English, the behaviour of a computer program when a function call is

performed.• Identify and author C/C++ language syntax to declare a function with no parameters.• Explain the role and behaviour of the return statement.• Identify and author C/C++ language syntax to declare a procedure.• Differentiate between situations in which a function should be declared instead of a proce-

dure, and vice versa.• Functionally decompose a problem, or algorithm, in a sensible manner.

8.1 Introduction

A function is an encapsulation of an algorithm (we discussed encapsulation in Chapter 1). It is away of referring, by name, to a set of instructions which accomplish a specific task.

We distinguish between defining a function, and using a function. The definition does notcause the function to do anything; it’s just a set of instructions, a potential, waiting to happen.The function only gets set into action if it is called by some other part of the program.

D.Neilson, M.Horsch, ”CMPT 111: Introduction to Computer Science and Programming” 59

CHAPTER 8. FUNCTIONS

A function can be called many times in a single program, and also by many different pro-grams. Recall from Chapter 5, we discussed mathematical functions like sin and pow. We didnot reveal the algorithms for these functions, but we showed how they can be used when needed.

Functions allow software developers to organize their programs. Without a way to organizethem, very large programs would be impossible to write, let alone fix or improve. Developerscan put code to do this here in this function, and code to do that in that other function.

Functions also allow software developer to solve very complex problems. If a complex prob-lem can be separated into independently solvable sub-problems, it is easier to solve. A functioncan be seen as the solution to a sub-problem, so the developer builds the solution to the complextask by building functions that solve the various sub-problems. This technique is very powerful,and is called functional decomposition.

A function that solves one very specific task is useful, but a function that can solve manytasks is more useful. For example, the function sin can compute the sin of any floating pointnumber. You may think that this is one task, but imagine a function that could only computethe sin of positive angles; or only angles between 0 and 2π; or only the very specific angle π/4.All of these are possible, and hopefully it is obvious that the first is the most useful, and the lastis almost useless. But it also works the other way. A function that computes sin of any angle isuseful, but a function that computed the value of sin would not be more useful if it also causedan animation of a dancing cow to appear on the computer screen.

If we accept a function as an encapsulated algorithm, then we have to give it ”input” and letit produce ”output.” The primary way we will give a function input is through its parameters(defined below). The primary way for a function to produce output is through its return value(defined below). When functions communicate with each other, it is through the parametersand return values. We are going to repeat that last bit because is is important. If you wantyour program to ”know” some piece of information/data, then you have to tell it through aparameter. Similarly, if you want your function to tell its caller some piece of information, thenit has to be told as the function’s return value.

Occasionally, a function may use cin or cout to communicate to the user, but functions cannotcommunicate to each other using the console. The console is not a bulletin board!

We have already shown you a little of how to use functions that are provided for you throughlibraries of code. All that remains is to show you how to define, and use, your own functions.

A function definition looks like this:✞ ☎/∗

Descr ipt ion :Generate a random i n t e g e r in the range {A, A+1 , . . . , B} i n c l u s i v e

Input :A −− lower bound on the rangeB −− upper bound on the range .

Output :re turns −− generated random value

Assumptions :A < B

∗/i n t randomRange ( i n t A, i n t B ){

// See documentation f o r c s t d l i b f o r rand ( ) funct ionreturn ( rand ( ) % ( B−A+1 ) ) + A;

}✝ ✆60 D.Neilson, M.Horsch, ”CMPT 111: Introduction to Computer Science and Programming”

CHAPTER 8. FUNCTIONS

A function definition contains five parts. We’ll discuss them briefly here, and then in more detailas this chapter progresses.

1. A comment block (starting with /* and ending with */ 10 lines later, in this example) thattells the reader what the function’s purpose is, what input it requires, and what output itprovides. The comment block here is very detailed, and covers everything a reader wouldneed to know. A professional software developer would put at least this much effort intodocumentation.

2. The function header is the line that reads int randomRange(int A, int B). It containsall of the information that a programmer needs to know to call the function. The header ismade up of 3 parts, in order from left to right:

• The return data type is the type of the value that is returned by the function. This exam-ple function returns a value with the int data type.

• Following the return data type is the function’s name. The name of a function followsthe same naming rules as variables. In this example, the name of the function israndomRange.

• Next comes parentheses that contain a comma-separated list of the function’s parame-ters. This example has two parameters: A and B, both of type int.

• The return type always appears first! Then the function name, then the parameter list.• Note that there is no semi-colon at the end of the function header when it is a part of

a function definition.

3. Finally, the function body is the block that appears after the header. This block is theprogram-code that is executed when the function is called. The code in the body mayuse the function parameters however you wish, and must provide a value for the function toreturn through a return statement.

A function definition must appear before any program code that uses it. This is consistentwith the ”define-before-use” approach that C is based on. For example, if function A calls func-tion B, then the definition of function B must appear before the definition of function A. Finally,a function definition must not be within any other programming construct.

Here’s a longer example. Notice that the function randomRange() is called in the functionplayerLives(). Therefore, the function randomRange() is defined first. Notice also that the func-tion playerLives() is called in the main program, so it is defined before main() (but after random-Range().✞ ☎# include <iostream># include <c s t d l i b > // For srand , and rand# include <ctime> // For timeusing namespace std ;

/∗Descr ipt ion :

Generate a random i n t e g e r in the range [A, B ] , i n c l u s i v eInput :

A −− lower bound on the rangeB −− upper bound on the range .

Output :re turns −− generated random value

Assumptions :

D.Neilson, M.Horsch, ”CMPT 111: Introduction to Computer Science and Programming” 61

CHAPTER 8. FUNCTIONS

A < B∗/i n t randomRange ( i n t A, i n t B ){

// See c s t d l i b documentation f o r rand ( ) funct ionreturn ( rand ( ) % ( B−A+1 ) ) + A;

}

/∗Descr ipt ion :

Randomly decide i f the player l i v e s or dies . P r i n t a messagei n d i c a t i n g success i f they l i v e .

Input :whichPassage −− word desc r ib ing the passage ( ex : ” f i r s t ” , ”dark ”)

Output :re turns −− t rue i f the player l i v e s on , f a l s e i f he/she dies

∗/bool playerLives ( s t r i n g whichPassage ){

/∗ Player has a 50% chance to survive the room .Can determine whether the player survives by generat inga uniformly d i s t r i b u t e d random number between 1 and 1 0 0 .I f the number i s bigger than 100−( s u r v i v a l r a t e ) thenthe player l i v e s . ∗/

i n t randomRoll = randomRange ( 1 , 1 0 0 ) ;i f ( randomRoll > 50){

cout << ”You got through the ” << whichPassage << ” passage . ”<< endl ;

re turn true ;}re turn f a l s e ;

}

i n t main ( ){

// Seed the random number generatorsrand ( time ( 0 ) ) ;// P r i n t the i n t r ocout << ”You awake in a dimly l i t room a f t e r a night of drinking ”

<< ”with some dwarves . ” << endl<< ”A grungy looking man i s in the room with you . He looks ”<< ”up at you , asks ” << endl<< ”\”Dwarves got you too ?\” , ges tures a t a passage in ”<< ” the e a s t wall , ” << endl<< ”and says \”Out ’ s t h a t way . Good luck .\” ” << endl << endl<< ”The passages are p i t c h black . You are l i k e l y to be eaten ”<< ”by a grue . ” << endl << endl ;

// Play the gamei f ( p layerLives ( ” f i r s t ” ) && playerLives ( ” s t i c k y ” ) &&

playerLives ( ” smelly ” ) && playerLives ( ” slimy ” ) ){

cout << ” Congratulat ions , you have made i t out a l i v e ! ” << endl ;cout << ”The barkeep i s wait ing f o r you with your b i l l from ”

<< ” l a s t night . ” << endl ;}e l s e

62 D.Neilson, M.Horsch, ”CMPT 111: Introduction to Computer Science and Programming”

CHAPTER 8. FUNCTIONS

{cout << ”You have been eaten by a grue . ” << endl ;

}re turn 0 ;

}✝ ✆We strongly encourage you to type this program out, and use a debugger to investigate how

it works.

8.1.1 The function main()

If you’ve been following along, then you will have noticed that we’ve been using a functioncalled main() since the first C++ program we showed you. This is a special function in one sense:When your program is started, the operating system on the computer starts your program bycalling main(). When your program is finished, the last thing it should do is return a value tothe operating system. In CMPT111, it is good enough to return 0 all the time, but in advancedcourses, you may learn about reasons to return other values.

All C and C++ programs must have one, and only one, main() function. It is defined in thelanguage that the main() function is the place that your program will always begin executing.

The function main() is not special in any other way. It’s just a function.

8.1.2 Function Documentation

Recall that comments are completely ignored by the compiler; so, strictly speaking, the commentblock immediately before the function header is not required for a program that works correctly.However, it is very good programming practice to include a comment block at the start of everyfunction definition that, at a minimum, contains: a description of what the function does, a briefdescription for each input and output, and any assumptions or restrictions placed on the input(for example, a sine function might require an angle be provided in radians). The intent of thiscomment block is to provide all of the information that a programmer will require to be able tounderstand what your function does, and how they can use your function. A good programmerdocuments everything they write. A poor programmer forces the readers to figure things out ontheir own. An excellent programmer documents the functions before they are actually written,as part of the design process.

8.1.3 Function Parameters

A function’s parameters are variables available within the function that are automatically ini-tialized when the function is called; they are initialized to contain the values of the arguments(recall that we call the data provided in the parentheses of a function call the arguments to thefunction) that the function was called with. There are two kinds of parameters in the C language:pass-by value parameters, and pass-by-reference parameters. Both kinds of parameters can providevariables with values for you to use in a function, but they do so in different ways. We are go-ing to discuss pass-by-value parameters now, and revisit pass-by-reference parameters when wediscuss arrays in Chapter 11.

D.Neilson, M.Horsch, ”CMPT 111: Introduction to Computer Science and Programming” 63

CHAPTER 8. FUNCTIONS

Pass-by-value Parameters

A pass-by-value parameter (PBV) copies a data value, that was provided as an argument whenthe function was called, into a new variable within the function; the name of this variable is thename provided in the declaration for the parameter. The argument for a PBV parameter can beany kind of data value (a variable, a literal, an expression, a function call, et cetera) because aPBV parameter makes a copy of the data value provided for it.

For example, consider the randomRange function provided above. Both of the parameters tothis function are PBV parameters; for now, all functions that you write will have pass-by-valueparameters. So, if you call this function, say with randomRange(0, 100), then the followinghappens:

1. Execution pauses exactly where the function call is made.2. A new environment is set up for randomRange to run in.3. Variables A and B are created in this new environment.4. The value 0 is copied into this new variable A (the first argument goes to the first parame-

ter).5. The value 100 is copied into this new variable B (the second argument goes to the second

parameter).6. Execution of randomRange begins.

Note that the 0 and 100 used as arguments in this example function call could have been anytype of data value, and the behaviour would have been identical (with the different data valuesused instead, of course).

When the return statement is reached in randomRange then execution of randomRangehalts, and the variables A and B that were created for the run of randomRange will be destroyed(losing whatever values were in them in the process).

No Parameters

The C language allows you to write functions that do not have any parameters. Functions withno parameters are useful when you want to do things such as printing out a message to the user,asking for and reading a data value from the console, et cetera. To declare a function with noparameters you can leave the list of parameters blank (the parentheses are still required).

When calling a function that has no parameters, you must still provide the parentheses afterthe function name, but there is nothing within them.

For example, this function:✞ ☎f l o a t g e t I n t e r e s t R a t e ( ){

f l o a t r a t e ;cout << ” Please enter the year ly i n t e r e s t r a t e : ” ;c in >> r a t e ;re turn r a t e ;

}✝ ✆could be called like this:✞ ☎

i n t e r e s t R a t e = g e t I n t e r e s t R a t e ( ) ;✝ ✆64 D.Neilson, M.Horsch, ”CMPT 111: Introduction to Computer Science and Programming”

CHAPTER 8. FUNCTIONS

8.1.4 The return Statement

The return statement inside of a function does three things:

• It provides the data value that is going to be returned by the function.• It immediately halts the execution of the function.• It causes execution of the program to resume at the place where the function was called.

The data value provided in the return statement must be the same data type as the return datatype of the function; type conversion, such as changing a float to an int, will be done automat-ically if possible. This data value may be provided in any way (via: a variable, an expression,another function call as part of an expression, et cetera).

Please make note of the syntax used for the return statement. The syntax is the word returnfollowed by a space, then the data value to be returned, and the statement is terminated with asemi-colon. The data value may be in parentheses, if you desire.All functions must return a value using a return statement.

8.2 Procedures

The data type void is a special data type that, quite literally, means ”nothing” – think of thephrase ”staring into the void.” A function may use void for its return data type; we will call afunction with a void return type a procedure to differentiate it (you could also call it a ”voidfunction”), but everything we have discussed about functions also holds true for procedures.

You should use a procedure when you design a sub-task that does something, but does notcalculate any sort of value to return. For instance, you might want to have a sub-task that printsout instructions for how to use your program; such a sub-task would print out text, but does notcalculate any value for the program to use.

In a procedure, the syntax of the return statement is slightly altered. Procedures have a voidreturn data type, and so they return nothing. As a result, the return statement in a proceduredoes not include a value (there is no value to return!), and is written simply as the word returnfollowed by a semi-colon. For example:✞ ☎/∗Descr ipt ion :

P r i n t s out the given year ly i n t e r e s t r a t e as part of a formatteds t r i n g .

Input :r a t e −− year ly i n t e r e s t ra te , in percent

Output :none

∗/void p r i n t I n t e r e s t R a t e ( f l o a t r a t e ){

cout << ”The year ly i n t e r e s t r a t e i s ” << r a t e << ”%” << endl ;re turn ;

}✝ ✆Since a procedure does not actually return a value, the return statement is not always re-

quired in one. There is an implied return statement at the end of the body of a procedure;if execution reaches the end of the procedure, then the procedure will return. So, the aboveexample can also be written as:

D.Neilson, M.Horsch, ”CMPT 111: Introduction to Computer Science and Programming” 65

CHAPTER 8. FUNCTIONS

✞ ☎/∗Descr ipt ion :

P r i n t s out the given year ly i n t e r e s t r a t e as part of a formatteds t r i n g .

Input :r a t e −− year ly i n t e r e s t ra te , in percent

Output :none

∗/void p r i n t I n t e r e s t R a t e ( f l o a t r a t e ){

cout << ”The year ly i n t e r e s t r a t e i s ” << r a t e << ”%” << endl ;}✝ ✆and the behaviour of it is absolutely identical to the example with the return statement.

In truth, the only reason you will ever need a return statement in a procedure is whenyou want to halt the execution of the procedure before the end of its body. Some opinions holdthat a function should have exactly one return statement, and that a procedure should have noexplicit return statements. This kind of dogmatic teaching is intended to prevent novices fromdeveloping bad habits. This should convince you that you need to understand the use of returnvery carefully, so that you can decide whether to be dogmatic yourself. The second author isdogmatic in this respect.

8.3 Common Pitfalls

There are some common mistakes that we see beginner programmers make with functions in theC language. We include them here for your information, and in the hopes that if you do makeone of these mistakes then you will have an easier time finding the source of the problem.

8.3.1 Additional Semi-colon

There is no semi-colon after the function header in a function definition. Recall that the semi-colonseparates whatever comes before from whatever comes after. So, placing a semi-colon afterthe function header will separate the header from the body, which is probably not intended(functions are not zombies!).

8.3.2 Misplaced Declaration

A function definition in the C language cannot be placed within any other programming construct– another function definition, a block of code, et cetera. So, definition similar to any of thefollowing are not allowed in C:✞ ☎void func1 ( i n t x ){

i n t func2 ( ){

re turn 1 ;}

}✝ ✆66 D.Neilson, M.Horsch, ”CMPT 111: Introduction to Computer Science and Programming”

CHAPTER 8. FUNCTIONS

✞ ☎void func1 ( i n t x )

i n t func2 ( ){

re turn 1 ;}

{}✝ ✆8.3.3 Must Declare Before Use

A function definition must appear in your program code before any calls to the function. Thecompiler for the C language reads your program’s source code from the top of the file, andworks its way down. Furthermore, it does not know what your function is until you tell it witha function definition. So, if it encounters a call to your function, and you have not declared itabove that point in your source file then the compiler will have an error.

8.3.4 No Types When Calling A Function

The return data type, and data types of a function’s parameters are required when declaring afunction. Once a function has been declared, the C compiler will remember what the returntype, and parameter types are. So, when calling a function, you do not include the data types ofthe values you are passing to it; the C compiler can remember.

Thus, for example, the randomRange function that we declared above would be called withsomething like the following (a, b, and value are all int variables that have already beendeclared, and initialized):✞ ☎

value = randomRange ( a , b ) ;value = randomRange ( 0 , b ) ;value = randomRange ( a , 100) + 2 0 ;value = 5 ∗ randomRange ( a +10 ,b + 1 0 0 ) ;✝ ✆

not any of the following:✞ ☎value = randomRange ( i n t a , i n t b ) ;value = i n t randomRange ( i n t a , i n t b ) ;value = i n t randomRange ( a , b ) ;value = randomRange ( 0 , i n t b + 2 ) ;✝ ✆

8.3.5 Declaring Variables as Function Parameters

A surprising (to us), but common, misconception among beginners is the idea that all of thevariables for a function must be declared as parameters. This could not be further from thetruth.

The code block that is a part of a function definition can contain completely new variabledeclarations, as well as if statements, loops, printing and reading actions, arithmetic, et cetera.Anything you need (except another function definition).

The parameters to a function are only for providing data values to the function. If you needto have some place to store values created by the function, then feel free to declare as manyvariables inside the function body as you wish.

D.Neilson, M.Horsch, ”CMPT 111: Introduction to Computer Science and Programming” 67

CHAPTER 8. FUNCTIONS

8.4 What the heck is a grue?

What light through yonder Google breaks...

68 D.Neilson, M.Horsch, ”CMPT 111: Introduction to Computer Science and Programming”