further control structures

111
1 Further Control Structures I will go over some important topics today. Loops and conditionals are essential for ones development in any programming language. We will look at the three types of looping mechanisms for do-while while We will also look again at the if statement only if it is required.

Upload: enid

Post on 06-Jan-2016

23 views

Category:

Documents


2 download

DESCRIPTION

Further Control Structures. I will go over some important topics today. Loops and conditionals are essential for ones development in any programming language. We will look at the three types of looping mechanisms for do-while while - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Further Control Structures

1

Further Control Structures

I will go over some important topics today. Loops and conditionals are essential for ones

development in any programming language. We will look at the three types of looping

mechanisms for do-while while

We will also look again at the if statement only if it is required.

Page 2: Further Control Structures

2

Week 4 Topics

Switch Statement for Multi-way Branching Can be achieved with an if statement This was previously looked at We have to be careful with “fall through” however

Do-While Statement for Looping For Statement for Looping Using break and continue statements This is used predominantly with the switch

statement

Page 3: Further Control Structures

3

Display a menu Simple Menus

1. Program displays a menu of choices

2. User enters a choice

3. Program responds to choice

4. Go back to to 1

Page 4: Further Control Structures

4

Display a menu Simple DisplayMenu() function

#include <iostream>

void DisplayMenu(void);

int main( ) {

return 0;}

function prototype consisting of

<type> function name (types of parameters);

So void here means no return type or parameters expected.

Page 5: Further Control Structures

5

Display a menu Simple DisplayMenu() function

#include <iostream>

void DisplayMenu(void);

int main() {

return 0;}

void DisplayMenu(void) {cout << “*********** MENU **************\n”;cout <<endl;cout << “ 1. Man United” << endl;cout << “ 2. Chelsea” << endl;cout << “ 3. Arsenal” << endl;cout << “ 4. Quit” << endl;cout << endl;cout << “Please choose 1, 2, 3 or 4 : “;

}

Definition:like a mini program or sub program

Page 6: Further Control Structures

6

Display a menu Simple DisplayMenu() function

#include <iostream>

void DisplayMenu(void);

int main() {int response;

DisplayMenu();

return 0;}

void DisplayMenu(void) {cout << “*********** MENU **************\n”;cout <<endl;cout << “ 1. Man United” << endl;cout << “ 2. Chelsea” << endl;cout << “ 3. Arsenal” << endl;cout << “ 4. Quit” << endl;cout << endl;cout << “Please choose 1, 2, 3 or 4 : “;

}

Function call from within main()

Prompt

Page 7: Further Control Structures

7

User enters choice

Prompt was part of function DisplayMenu use cin to get a response from user. The function is invoked by a call from

another function, in this case the calling function is main()

The call is just a writing of the function name in this case, with no parameters passed to this function

Page 8: Further Control Structures

8

Display a menu and Get response

#include <iostream>

void DisplayMenu(void);

int main() {int response;

DisplayMenu();cin >> response;return 0;

}

void DisplayMenu(void) {cout << “*********** MENU **************\n”;cout <<endl;cout << “ 1. Man United” << endl;cout << “ 2. Chelsea” << endl;cout << “ 3. Arsenal” << endl;cout << “4. Quit” << endl;cout << endl;cout << “Please choose 1, 2 or 3 : “;

}

Get response

Page 9: Further Control Structures

9

Process the response by using the switch statement

Page 10: Further Control Structures

10

What isthe switch Statement

Similar to the if statement Can list any number of branches Used in place of nested if statements Used only with integer expressions

(true/false or int or char) Avoids confusion of deeply nested if

statements

Page 11: Further Control Structures

The switchswitch Statement

Syntaxswitch (expression) {

case value1: statement1;break;

case value2: statement2;break;case valueN: statementN;break;

default: statement;}

expression must return an integer value, i.e. be an integer

Page 12: Further Control Structures

The switchswitch Statementwith char expression

switch (choice){case 1: cout << “The greatest ” << endl;

break;case 2: cout << “Exciting team ”<< endl;

breakcase 3: cout << “Boring ” << endl;

break;case 4: cout << “Bye Bye” << endl;}

//next statement

Page 13: Further Control Structures

What is the purpose of the break statement?The breakbreak Statement prevents “fall through”it makes the computer jump out of the current block, recall that the switch statement will execute all statements below the point of entering the statement. This can be a problem.

Page 14: Further Control Structures

The switchswitch Statement illustrate fall through again

switch (choice){case 1: cout << “The greatest ” << endl;case 2: cout << “Exciting team ”<< endl;case 3: cout << “Boring ” << endl;case 4: cout << “Bye Bye << endl;}

Page 15: Further Control Structures

The switchswitch Statement

What will be the output when the user enters 1?

The greatest

Exciting team

Boring

Bye Bye

Page 16: Further Control Structures

The switchswitch Statement

What will be the output when the user enters 2?

Exciting team

Boring

Bye Bye

Page 17: Further Control Structures

The switchswitch Statement

What will be the output when the user enters 3?

Boring

Bye Bye

Page 18: Further Control Structures

The switchswitch Statement

What will be the output when the user enters 4?

Bye Bye

Page 19: Further Control Structures

Classic use of switchswitch Statements: for Menu processing

* * * * Menu * * * *

1. Man United

2. Chelsea

3. Arsenal

4. Quit

Choose either 1, 2, 3 or 4:

Page 20: Further Control Structures

20

Example program to Demo#include <iostream> //see displaymenu3.cppUsing namespace std;void DisplayMenu(void);

int main(void) {int choice;DisplayMenu();cin >> choice;

switch (choice) {case 1: cout << “The greatest“ << endl;case 2: cout << “Exciting team“ << endl;case 3: cout << “Boring“ << endl;case 4: cout << “Bye Bye << endl;};return 0;

}void DisplayMenu(void) {

cout << "*********** MENU **************\n";cout <<endl;cout << " 1. Man United" << endl;cout << " 2. Chelsea" << endl;cout << " 3. Arsenal" << endl;cout << endl;cout << "Please choose 1, 2 or 3 : ";

}

Page 21: Further Control Structures

The switchswitch Default Statement captures errors or perform default action

e.g. if user enter any other number

switch (choice){case 1: cout << “The greatest ” << endl;

break;case 2: cout << “Exciting team ”<< endl;

break;case 3: cout << “Boring ” << endl;

break;case 4: cout << “Bye Bye “ << endl;

break;default: “Incorrect choice” << endl;}

Page 22: Further Control Structures

22

Nested Switch StatementsFor example:switch( CarType ) { case MONDEO:  

switch( EngineCapacity)    {    case 1500:cout << “This is underpowered “;

break;    case 1800: cout << “This is just right”;       

break;    case 2000: cout<<“This is expensive to run”;};

case FIESTA:  break; default:    cout << “Unknown model”;}

Page 23: Further Control Structures

23

Problems with switch

Strange rules, once a condition is tested true execution proceeds until break or end of switch. Control “falls through” the switch Get in the habit of always putting breaks in and

putting a default condition in. Less satisfactory to use where floats or

Boolean expressions are tested. Putting in semi colon ‘;’after case rather than

colon ‘:’

Page 24: Further Control Structures

24

Recall Purpose of Loops/Repetition

To apply the same steps again and again to a block of statements.

Recall a block of statement is one or more statement, block usually defined by braces { … } with syntactically correct statements inside.

Page 25: Further Control Structures

25

Most Common Uses of LoopsYou should master all these! For counting For accumulating, i.e. summing For searching For sorting For displaying tables For data entry – from files and users For menu processing For list processing

Page 26: Further Control Structures

26

Types of loops

while

for

do..while

Page 27: Further Control Structures

27

C/C++ Loop Structures Pre-test (the test is made before entering the

loop) while loops

– general purpose– Event controlled (variable condition)

for loops – When you know how many times (fixed condition)– When you process arrays (more in later lectures)

Post-test (the test is done at the end of the loop) do … while loops

– When you do not know how many times, but you know you need at least one pass.

– Data entry from users

Page 28: Further Control Structures

28

Do-While Statement

Is a looping control structure in which the loop condition is tested after each iteration of the loop.

SYNTAX

do

{

Statement

} while (Expression) ; //note semi colon

Loop body statement can be a single statement or a block.

Page 29: Further Control Structures

29

void GetYesOrNo ( char response )

//see UseofFunction1.cpp// Inputs a character from the user

// Postcondition: response has been input // && response == ‘y’ or ‘n’{

do{

cin >> response ; // skips leading whitespace

if ( ( response != ‘y’ ) && ( response != ‘n’ ) ) cout << “Please type y or n : “ ;

} while ( ( response != ‘y’ ) && ( response != ‘n’ ) ) ;}

Function Using Do-While

29

Page 30: Further Control Structures

30

Do-While Loop vs. While Loop

POST-TEST loop (exit-condition)

The looping condition is tested after executing the loop body.

Loop body is always executed at least once.

PRE-TEST loop (entry-condition)

The looping condition is tested before executing the loop body.

Loop body may not be executed at all.

Page 31: Further Control Structures

31

Do-While Loop

When the expression is tested and found to be false, the loop is exited and control passes to the statement that follows the do-while statement.

Statement

Expression

DO

WHILE

FALSE

TRUE

Page 32: Further Control Structures

The for Statement Syntax

Example:for (count=1; count < 7; count++)

{cout << count << endl;

}//next C++ statements;

start condition change expressionwhile condition

Page 33: Further Control Structures

The for Statement Used as a counting loop Used when we can work out in advance the

number of iterations, i.e. the number of times that we want to loop around.

Semicolons separate the items in the for loop block There is no semi colon at the end of the for loop

definition at the beginning of the statement

Page 34: Further Control Structures

int num;cout << "NUMBER\tSQUARE\tCUBE\n“; cout << "------\t------\t----\n";

for (num = 1; num < 11; num++) {cout << num << “\t“;cout << num * num << “\t“;cout << num * num * num<<“\n";

}//see useofFunction2.cpp

A Simple ExampleCreate a table with a for loop

NUMBER SQUARE CUBE---------- ---------- ------ 1 1 1 2 4 8 . . . . . . 10 100 1000

Page 35: Further Control Structures

for and if Statements working together.

Simple search for divisors Given an integer number find all the

numbers that divide exactly into it (including 1 and itself).

e.g. if number = 12, divisors are 1,2,3,4,6,12

Think I canuse %

operator to find divisors

Page 36: Further Control Structures

36

Solution Design

1. Get the number from user

2. By starting with check number=1 and finish with number (is this efficient?)1. find the remainder of dividing number with

current check number

2. if remainder is 0 display current check number as a divisor.

3. otherwise do not display anything

Page 37: Further Control Structures

37

Program fragment for finding divisors of an integer

cout << “Enter an integer :”;cin >> number;

for (j = 1; j <= number; j = j + 1)

{ if (number % j == 0)

{ cout << j << “ is a divisor of “;

cout << number << endl;

}

}//see useofFunction3.cpp

Page 38: Further Control Structures

for (j = 0, j < n, j = j + 3)

// commas used when semicolons needed

for (j = 0; j < n)

// three parts needed

for (j = 0; j >= 0; j++)

?????what is wrong here ?????

for (j=0, j=10; j++);

Common errors in constructing for Statements

Page 39: Further Control Structures

39

Infinite loops example 1

for (j=0; j>=0; j++) {

cout << j << endl;

}

What will happen here

//see infiniteloop1.cpp

Page 40: Further Control Structures

40

Loop design7 Loop Design Factors1. What is the condition that ends the loop?2. How should the condition be setup or primed?3. How should the condition be updated?4. What processes are being repeated?5. How do you set up the processes?

e.g. initialise event counters or accumulators

6. How is the process updated? e.g. update accumulators and counters

7. What is the expected state of the program at exit from loop?

Page 41: Further Control Structures

41

Programming convention Use of integers called i,j,k You will see them all the time. Most commonly used as loop control

variables Conventionally used for counters

We will see later that counters often have a dual use as array indices.

arrays to be discussed in later lectures When you see i,j,k declared expect to see a

loop!

Page 42: Further Control Structures

42

Example of Repetition

int n;

for ( int i = 1 ; i <= n ; i++ ) { cout << i << “ Potato” << endl;}

//see usefor1.cpp// useofFunction5.cpp

Page 43: Further Control Structures

43

Example of Repetition num

int n;

for ( int i = 1 ; i <= n ; i++ )

cout << i << “ Potato” << endl;

OUTPUT

?

Page 44: Further Control Structures

44

Example of Repetition num

OUTPUT

1

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << num << “Potato” << endl;

Page 45: Further Control Structures

45

Example of Repetition num

OUTPUT

1

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << num << “Potato” << endl;

true

Page 46: Further Control Structures

46

Example of Repetition num

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << num << “Potato” << endl;

OUTPUT

1

1Potato

Page 47: Further Control Structures

47

Example of Repetition num

OUTPUT

2

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << num << “Potato” << endl;

1Potato

Page 48: Further Control Structures

48

Example of Repetition num

OUTPUT

2

true

1Potato

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << num << “Potato” << endl;

Page 49: Further Control Structures

49

Example of Repetition num

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << num << “Potato” << endl;

OUTPUT

2

1Potato

2Potato

Page 50: Further Control Structures

50

Example of Repetition num

OUTPUT

3

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << num << “Potato” << endl;

1Potato

2Potato

Page 51: Further Control Structures

51

Example of Repetition num

OUTPUT

3

true

1Potato

2Potato

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << num << “Potato” << endl;

Page 52: Further Control Structures

52

Example of Repetition num

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << num << “Potato” << endl;

OUTPUT

3

1Potato

2Potato

3Potato

Page 53: Further Control Structures

53

Example of Repetition num

OUTPUT

4

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << num << “Potato” << endl;

1Potato

2Potato

3Potato

Page 54: Further Control Structures

54

Example of Repetition num

OUTPUT

4

false

1Potato

2Potato

3Potato

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << num << “Potato” << endl;

Page 55: Further Control Structures

55

Example of Repetition num

When the loop control condition is evaluated and has value false, theloop is said to be “satisfied” and control passes to the statementfollowing the for statement.

4

falseint num;

for ( num = 1 ; num <= 3 ; num++ )

cout << num << “Potato” << endl;

Page 56: Further Control Structures

56

The output was:

1Potato2Potato3Potato

Page 57: Further Control Structures

Nested Loops

Recall when a control structure is contained within another control structure, the inner one is said to be nested.

for ...if ...

for ...for...

You may have repetition within decision and vice versa.

Page 58: Further Control Structures

Example //see nested1.cpp

int row,col;

for (row = 0; row < 5; row++)

{

cout << "\n" <<row;

for (col = 1; col <= 3; col++)

{

cout <<"\t" << col;

}

cout << "\t**";

}

Nested Loops - Ex.1for within for

Page 59: Further Control Structures

59

CAUTION!What is the output from this

loop?int count;

for (count = 0; count < 10; count++) ;

{

cout << “”;

}

//see useforloop2.cpp

Page 60: Further Control Structures

60

no output from the for loop! Why? the ; right after the ( ) means that the body

statement is a null statement in general, the Body of the for loop is whatever

statement immediately follows the ( ) that statement can be a single statement, a

block, or a null statement actually, the code outputs one * after the loop

completes its counting to 10

Infinite loop example 2OUTPUT

*

Page 61: Further Control Structures

Output0 1 2 3 **

1 1 2 3 **

2 1 2 3 **

3 1 2 3 **

4 1 2 3 **

Nested Loops – Example 1

variable row changes from 0 to 4

variable col changes from 1 to 3 for every

time row changes

Page 62: Further Control Structures

62

Break Statement Revisited

break statement can be used with Switch or any of the 3 looping structures

it causes an immediate exit from the Switch, while, do-while, or for statement in which it appears

if the break is inside nested structures, control exits only the innermost structure containing it

Page 63: Further Control Structures

63

Continue Statement

is valid only within loops

terminates the current loop iteration, but not the entire loop

in a for or while, continue causes the rest of the body statement to be skipped--in a for statement, the update is done

in a do-while, the exit condition is tested, and if true, the next loop iteration is begun

Page 64: Further Control Structures

The break Statementint j = 40;while (j < 80){ j += 10; if (j == 70) break; cout << “j is “ << j<< ‘\n’;

}

cout << “We are out of the loop.\n”;

//see useBreak1.cpp

j is 50

j is 60

We are out of the loop.

Page 65: Further Control Structures

The continue Statementint j = 40;while (j < 80){

j += 10;if (j == 70)

continue; //skips the 70cout << “j is “ << j<< ‘\n’;

}//see UseContinue1.cpp

cout << “We are out of the loop” << endl;

j is 50

j is 60

j is 80

We are out of the loop.

Page 66: Further Control Structures

break and continue

while ( - - - ){

statement 1;if( - - - )

continuestatement 2;

}statement 3;

while ( - - - ){

statement 1;if( - - - )

breakstatement 2;

}statement 3;

Page 67: Further Control Structures

67

Break and Continue

Now see UseContinue1.cpp

Page 68: Further Control Structures

68

Functions and Program Structure

A function is a ``black box'' that we have locked part of our program into.

The idea behind a function is that it compartmentalizes part of the program, and in particular, that the code within the function has some useful properties:

Page 69: Further Control Structures

69

More on functions

It performs some well-defined task, which will be useful to other parts of the program.

It might be useful to other programs as well; that is, we might be able to reuse it (and without having to rewrite it).

The rest of the program does not have to know the details of how the function is implemented.

This can make the rest of the program easier to think about.

Page 70: Further Control Structures

70

More on functions The function performs its task well. It may be written to do a little more than is

required by the first program that calls it, with the anticipation that the calling program (or some other program) may later need the extra functionality or improved performance.

(It is important that a finished function do its job well, otherwise there might be a reluctance to call it, and it therefore might not achieve the goal of reusability.)

Page 71: Further Control Structures

71

Functions

By placing the code to perform the useful task into a function, and simply calling the function in the other parts of the program where the task must be performed, the rest of the program becomes clearer:

rather than having some large, complicated, difficult-to-understand piece of code repeated wherever the task is being performed, we have a single simple function call, and the name of the function reminds us which task is being performed.

Page 72: Further Control Structures

72

Functions

Since the rest of the program does not have to know the details of how the function is implemented, the rest of the program does not care if the function is reimplemented later, in some different way (as long as it continues to perform its same task, of course!).

This means that one part of the program can be rewritten, to improve performance or add a new feature (or simply to fix a bug), without having to rewrite the rest of the program.

Page 73: Further Control Structures

73

More on functions

Functions are probably the most important weapon in our battle against software complexity.

You will want to learn when it is appropriate to break processing out into functions (and also when it is not), and how to set up function interfaces to best achieve the qualities mentioned above: reuseability, information hiding, clarity, and maintainability

Page 74: Further Control Structures

74

4.1 Function Basics

So what defines a function? It has a name that you call it by, and a

list of zero or more arguments or parameters that you hand to it for it to act on or to direct its work; it has a body containing the actual instructions (statements).

Page 75: Further Control Structures

75

Functions

For carrying out the task the function is supposed to perform; and it may give you back a return value, of a particular type.

Here is a very simple function, which accepts one argument, multiplies it by 2, and hands that value back:

Page 76: Further Control Structures

76

A simple function

int multbytwo(int x)

{

int retval; //a local variable

retval = 2*x;

return retval;

}

Page 77: Further Control Structures

77

Explaining the function

On the first line we see the return type of the function (int), the name of the function (multbytwo), and a list of the function's arguments, enclosed in parentheses.

Each argument has both a name and a type; multbytwo accepts one argument, of type int, named x.

The name x is arbitrary, and is used only within the definition of multbytwo.

Page 78: Further Control Structures

78

Explaining the function

The caller of this function only needs to know that a single argument of type int is expected; the caller does not need to know what name the function will use internally to refer to that argument.

(In particular, the caller does not have to pass the value of a variable named x.)

Page 79: Further Control Structures

79

Explaining the function

Next we see, surrounded by the familiar braces, the body of the function itself.

This function consists of one declaration (of a local variable retval) and two statements.

The first statement is a conventional expression statement, which computes and assigns a value to retval, and the second statement is a return statement, which causes the function to return to its caller, and also specifies the value which the function returns to its caller.

Page 80: Further Control Structures

80

Explaining the function

The return statement can return the value of any expression, so we do not really need the local retval variable; the function could be altered to

int multbytwo(int x){

return 2*x;}

Page 81: Further Control Structures

81

Calling the function

How do we call a function? We have been doing so informally since

day one, but now we have a chance to call one that we have written, in full detail.

Here is a tiny skeletal program to call multby2:

Page 82: Further Control Structures

82

Calling the function

#include <iostream>using namespace std;int multbytwo(int); // function prototypeint main(){int i, j;i = 3;j = multbytwo(i);cout << j << endl;return 0;}

Page 83: Further Control Structures

83

Explaining the call

This looks much like our other test programs, with the exception of the new line

int multbytwo(int); This is a function prototype declaration. It is an external declaration, in that it declares

something which is defined somewhere else. (We have already seen the defining instance

of the function multbytwo, but maybe the compiler has not seen it yet.)

Page 84: Further Control Structures

84

Explaining the call

The function prototype declaration contains the three pieces of information about the function that a caller needs to know: the function's name, return type, argument type(s).

Page 85: Further Control Structures

85

Explanation

Since we do not care what name the multbytwo function will use to refer to its first argument, we do not need to mention it.

On the other hand, if a function takes several arguments, giving them names in the prototype may make it easier to remember which is which, so names may optionally be used in function prototype declarations.

Page 86: Further Control Structures

86

Function prototypes

The presence of the function prototype declaration lets the compiler know that we intend to call this function, multbytwo.

The information in the prototype lets the compiler generate the correct code for calling the function, and also enables the compiler to check up on our code (by making sure, for example, that we pass the correct number of arguments to each function we call).

Page 87: Further Control Structures

87

Function prototypes

Down in the body of main, the action of the function call should be obvious: the line

j = multbytwo(i);

Page 88: Further Control Structures

88

Calling the function

calls multbytwo, passing it the value of i as its argument.

When multbytwo returns, the return value is assigned to the variable j.

Notice that the value of main's local variable i will become the value of multbytwo's parameter x; this is absolutely not a problem, and is a normal sort of affair.

Page 89: Further Control Structures

89

Calling the function

This example is written out in ”longhand,” to make each step equivalent.

The variable i is not really needed, since we could just as well call

j = multbytwo(3);

And the variable j is not really needed, either, since we could just as well call

cout << multbytwo(3);

Page 90: Further Control Structures

90

More on this function

Here, the call to multbytwo is a subexpression which serves as the argument to cout.

The value returned by multbytwo is passed immediately to cout.

Here, as in general, we see the flexibility and generality of expressions in C++.

An argument passed to a function may be an arbitrarily complex subexpression, and a function call is itself an expression which may be embedded as a subexpression within arbitrarily complicated surrounding expressions.

Page 91: Further Control Structures

91

More on this function

We should say a little more about the mechanism by which an argument is passed down from a caller into a function.

Formally, C++ is call by value, which means that a function receives copies of the values of its arguments

Page 92: Further Control Structures

92

Passing parameters

We can illustrate this with an example. Suppose, in our implementation of multbytwo,

we had eliminated the unnecessary retval variable like this:

int multbytwo(int x){ x = 2*x;

return x;}

Page 93: Further Control Structures

93

Passing parameters

We might wonder, if we wrote it this way, what would happen to the value of the variable i when we called the function

j = multbytwo(i); When our implementation of multbytwo

changes the value of x, does that change the value of i up in the caller?

The answer is no. x receives a copy of i's value, so when we change x we do not change i.

Page 94: Further Control Structures

94

Passing parameters

However, there is an exception to this rule.

When the argument you pass to a function is not a single variable, but is rather an array, the function does not receive a copy of the array, and it therefore can modify the array in the caller.

Page 95: Further Control Structures

95

Passing parameters

The reason is that it might be too expensive to copy the entire array, and furthermore, it can be useful for the function to write into the caller's array, as a way of handing back more data than would fit in the function's single return value.

We will see an example of an array argument (which the function deliberately writes into) in future lectures.

Page 96: Further Control Structures

96

4.2 Function Prototypes

In modern C++ programming, it is considered good practice to use prototype declarations for all functions that you call.

As we mentioned, these prototypes help to ensure that the compiler can generate correct code for calling the functions, as well as allowing the compiler to catch certain mistakes you might make.

Page 97: Further Control Structures

97

4.2 Function Prototypes

Strictly speaking, however, prototypes are optional.

If you call a function for which the compiler has not seen a prototype, the compiler will do the best it can, assuming that you are calling the function correctly.

If prototypes are a good idea, and if we are going to get in the habit of writing function prototype declarations for functions we call that we have written.

Page 98: Further Control Structures

98

Function prototypes

Such as multbytwo, what happens for library functions such as cout? Where are their prototypes? The answer is in the line

#include <iostream> We have been including at the top of all of our

programs iostream is conceptually a file full of external declarations and other information pertaining to the ``Standard I/O'' library functions, including cout.

The #include directive (which we have been using) arranges that all of the declarations within iostream are considered by the compiler, rather as if we had typed them all in ourselves

Page 99: Further Control Structures

99

4.3 Function Philosophy

What makes a good function? The most important aspect of a good

``building block'' is that have a single, well-defined task to perform.

When you find that a program is hard to manage, it is often because it has not been designed and broken up into functions “cleanly”.

Two obvious reasons for moving code down into a function are because:

Page 100: Further Control Structures

100

4.3 Function Philosophy

1. It appeared in the main program several times, such that by making it a function, it can be written just once, and the several places where it used to appear can be replaced with calls to the new function.

2. The main program was getting too big, so it could be made (presumably) smaller and more manageable by lopping part of it off and making it a function.

Page 101: Further Control Structures

101

Functions

These two reasons are important, and they represent significant benefits of well-chosen functions, but they are not sufficient to automatically identify a good function. As we have been suggesting, a good function has at least these two additional attributes:

3. It does just one well-defined task, and does it well. 4. Its interface to the rest of the program is clean and

narrow. Attribute 3 is just a restatement of two things we said

above. Attribute 4 says that you should not have to keep

track of too many things when calling a function.

Page 102: Further Control Structures

102

Functions

If you know what a function is supposed to do, and if its task is simple and well-defined, there should be just a few pieces of information you have to give it to act upon, and one or just a few pieces of information which it returns to you when it is done.

If you find yourself having to pass lots and lots of information to a function, or remember details of its internal implementation to make sure that it will work properly this time, it is often a sign that the function is not sufficiently well-defined.

Page 103: Further Control Structures

103

functions

A poorly-defined function may be an arbitrary chunk of code that was ripped out of a main program that was getting too big, such that it essentially has to have access to all of that main function's local variables.

The whole point of breaking a program up into functions is so that you do not have to think about the entire program at once; ideally, you can think about just one function at a time.

Page 104: Further Control Structures

104

Functions

We say that a good function is a ``black box,'' which is supposed to suggest that the ``container'' it is in is opaque--callers can not see inside it (and the function inside can not see out).

When you call a function, you only have to know what it does, not how it does it.

Page 105: Further Control Structures

105

Functions

When you are writing a function, you only have to know what it is supposed to do, and you do not have to know why or under what circumstances its caller will be calling it.

When designing a function, we should perhaps think about the callers just enough to ensure that the function we are designing will be easy to call, and that we are not accidentally setting things up so that callers will have to think about any internal details.

Page 106: Further Control Structures

106

Functions

Some functions may be hard to write (if they have a hard job to do, or if it is hard to make them do it truly well), but that difficulty should be compartmentalized along with the function itself.

Once you have written a ``hard'' function, you should be able to sit back and relax and watch it do that hard work on call from the rest of your program.

It should be pleasant to notice (in the ideal case) how much easier the rest of the program is to write, now that the hard work can be deferred to this workhorse function.

Page 107: Further Control Structures

107

Functions

In fact, if a difficult-to-write function's interface is well-defined, you may be able to get away with writing a quick-and-dirty version of the function first, so that you can begin testing the rest of the program, and then go back later and rewrite the function to do the hard parts.

As long as the function's original interface anticipated the hard parts, you will not have to rewrite the rest of the program when you fix the function.

Page 108: Further Control Structures

108

Functions

What I have been trying to say in the preceding few paragraphs is that functions are important for far more important reasons than just saving typing.

Sometimes, we will write a function which we only call once, just because breaking it out into a function makes things clearer and easier.

If you find that difficulties pervade a program, that the hard parts can not be buried inside black-box functions and then forgotten about; if you find that there are hard parts which involve complicated interactions among multiple functions, then the program probably needs redesigning.

Page 109: Further Control Structures

109

Functions

For the purposes of explanation, we have been seeming to talk so far only about ``main programs'' and the functions they call and the rationale behind moving some piece of code down out of a ``main program'' into a function.

But in reality, there is obviously no need to restrict ourselves to a two-tier scheme.

Any function we find ourselves writing will often be appropriately written in terms of sub-functions, sub-sub-functions, etc. (Furthermore, the ``main program,'' main(), is itself just a function.)

Page 110: Further Control Structures

110

More on functions

It performs some well-defined task, which will be useful to other parts of the program.

It might be useful to other programs as well; that is, we might be able to reuse it (and without having to rewrite it).

The rest of the program does not have to know the details of how the function is implemented.

This can make the rest of the program easier to think about.

Page 111: Further Control Structures

111

More on functions

The function performs its task well. It may be written to do a little more than is required by the first program that calls it, with the anticipation that the calling program (or some other program) may later need the extra functionality or improved performance.

It is important that a finished function do its job well, otherwise there might be a reluctance to call it, and it therefore might not achieve the goal of reusability.