Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C++ For Dummies (2004) [eng].pdf
Скачиваний:
84
Добавлен:
16.08.2013
Размер:
8.09 Mб
Скачать

Chapter 6

Creating Functions

In This Chapter

Writing functions

Passing data to functions

Naming functions with different arguments

Creating function prototypes

Working with include files

The programs developed in prior chapters have been small enough that they can be easily read as a single unit. Larger, real-world programs can be many thousands (or millions!) of lines long. Developers need to break up

these monster programs into smaller chunks that are easier to conceive, develop, and maintain.

C++ allows programmers to divide their code into exactly such chunks (known as functions). As long as a function has a simple description and a well-defined interface to the outside world, it can be written and debugged without worrying about the code that surrounds it.

This divide-and-conquer approach reduces the difficulty of creating a work­ ing program of significant size. This is a simple form of encapsulation — see Chapter 15 for more details on encapsulation.

Writing and Using a Function

Functions are best understood by example. This section starts with the example program FunctionDemo, which simplifies the NestedDemo program I discussed in Chapter 5 by defining a function to contain part of the logic. Then this section explains how the function is defined and how it is invoked, using FunctionDemo as a pattern for understanding both the problem and the solution.

80

Part II: Becoming a Functional C++ Programmer

The NestedDemo program in Chapter 5 contains an inner loop (which accu­ mulates a sequence of numbers) surrounded by an outer loop (which repeats the process until the user quits). Separating the two loops would simplify the program by allowing the reader to concentrate on each loop independently.

The following FunctionDemo program shows how NestedDemo can be simpli­ fied by creating the function sumSequence().

Function names are normally written with a set of parentheses immediately following the term, like this:

// FunctionDemo - demonstrate the use of functions

//

by breaking the inner loop of the

//

NestedDemo program off into its own

//

function

#include <cstdio>

#include <cstdlib>

#include <iostream>

using namespace std;

// sumSequence - add a sequence of numbers entered from

//

the keyboard until the user enters a

//

negative number.

//

return - the summation of numbers entered

int sumSequence(void)

{

// loop forever

 

 

int accumulator = 0;

 

for(;;)

 

{

//fetch another number int value = 0;

cout << “Enter next number: “; cin >> value;

//if it’s negative...

if (value < 0)

{

// ...then exit from the loop break;

}

//...otherwise add the number to the

//accumulator

accumulator= accumulator + value;

}

// return the accumulated value return accumulator;

}

int main(int nNumberofArgs, char* pszArgs[])

{

Chapter 6: Creating Functions

81

cout << “This program sums multiple series\n”

<<“of numbers. Terminate each sequence\n”

<<“by entering a negative number.\n”

<<“Terminate the series by entering two\n”

<<“negative numbers in a row\n”

<<endl;

//accumulate sequences of numbers...

int accumulatedValue; for(;;)

{

//sum a sequence of numbers entered from

//the keyboard

cout << “Enter next sequence” << endl; accumulatedValue = sumSequence();

//terminate the loop if sumSequence() returns

//a zero

if (accumulatedValue == 0)

{

break;

}

// now output the accumulated result cout << “The total is “

<<accumulatedValue

<<“\n”

<<endl;

}

cout << “Thank you” << endl;

//wait until user is ready before terminating program

//to allow the user to see the program results system(“PAUSE”);

return 0;

}

Defining the sumSequence() function

The statement int sumSequence(void) begins the definition of the sumSequence() function. The block of code contained in the braces is the function body. The function sumSequence() accumulates a sequence of values entered from the keyboard. This code section is identical to that found in the inner loop of NestedDemo.

82

Part II: Becoming a Functional C++ Programmer

Calling the function sumSequence()

Let’s concentrate on the main program contained in the braces following main(). This section of code looks similar to the outer loop in NestedDemo.

The main difference is the expression accumulatedValue = sumSequence(); that appears where the inner loop would have been. The sumSequence() statement invokes the function of that name. A value returned by the function is stored in the variable accumulatedValue. Then this value is displayed. The main program continues to loop until sumSequence() returns a sum of zero, which indicates that the user has finished calculating sums.

Divide and conquer

The FunctionDemo program has split the outer loop in main() from the inner loop into a function sumSequence(). This division wasn’t arbitrary: sumSequence() performs a separate role — worth considering by itself — apart from the control features within FunctionDemo.

A good function is easy to describe. You shouldn’t have to use more than a single sentence, with a minimum of such words as and, or, unless, or but. For example, here’s a simple, straightforward definition:

“The function sumSequence accumulates a sequence of integer values entered by the user.”

This definition is concise and clear. It’s a world away from the ContinueDemo program description:

“sums a sequence of positive values AND generates an error if the user enters a negative number AND displays the sum AND starts over again until the user enters two zero-length sums.”

The output of a sample run of this program appears much like that generated by the NestedDemo program, as follows:

This program sums multiple series of numbers. Terminate each sequence by entering a negative number. Terminate the series by entering two negative numbers in a row

Enter next sequence

Enter next number: 1

Enter next number: 2