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

Chapter 6: Creating Functions

83

Enter next number: 3

Enter next number: -1

The total is 6

Enter next sequence

Enter next number: 1

Enter next number: 2

Enter next number: -1

The total is 3

Enter next sequence

Enter next number: -1

Thank you

Press any key to continue . . .

Understanding the Details of Functions

Functions are so fundamental to creating C++ programs that getting a handle on the details of defining, creating, and testing them is critical. Armed with the example FunctionDemo program, consider the following definition of function:

A function is a logically separated block of C++ code. The function construct has the following form:

<return type> name(<arguments to the function>)

{

// ...

return <expression>;

}

The arguments to a function are values that can be passed to the function to be used as input information. The return value is a value that the function returns. For example, in the call to the function square(10), the value 10 is an argument to the function square(). The returned value is 100.

Both the arguments and the return value are optional. If either is absent, the keyword void is used instead. That is, if a function has a void argument list, the function does not take any arguments when called (this was the case with the FunctionDemo program). If the return type is void, the function does not return a value to the caller.

In the example FunctionDemo program, the name of the function is sumSequence(), the return type is int, and no arguments exist.

84

Part II: Becoming a Functional C++ Programmer

The default argument type to a function is void, meaning that it takes no arguments. A function int fn(void) may be declared as int fn().

The function construct made it possible for me to write two distinct parts of the FunctionDemo program separately. I concentrated on creating the sum of a sequence of numbers when writing the sumSequence() function. I didn’t think about other code that may call the function.

Similarly, when writing main(), I concentrated on handling the summation returned by sumSequence() while thinking only of what the function did — not how it worked.

Understanding simple functions

The simple function sumSequence() returns an integer value that it calcu­ lates. Functions may return any of the regular types of variables. For exam­ ple, a function might return a double or a char (int, double, and char are a few of the variable types discussed in Chapter 2).

If a function returns no value, the return type of the function is labeled void.

A function may be labeled by its return type — for example, a function that returns an int is often known as an integer function. A function that returns no value is known as a void function.

For example, the following void function performs an operation, but returns no value:

void echoSquare()

{

int value;

cout << “Enter a value:”;

cin >> value;

cout << “\n The square is:” << (value * value) << “\n”; return;

}

Control begins at the open brace and continues through to the return state­ ment. The return statement in a void function is not followed by a value.

The return statement in a void function is optional. If it isn’t present, execu­ tion returns to the calling function when control encounters the close brace.

Chapter 6: Creating Functions

85

Understanding functions with arguments

Simple functions are of limited use because the communication from such functions is one-way — through the return value. Two-way communication is through function arguments.

Functions with arguments

A function argument is a variable whose value is passed to the calling function during the call operation. The following SquareDemo example program defines and uses a function square() that returns the square of a double precision float passed to it:

//SquareDemo - demonstrate the use of a function

//which processes arguments

#include <cstdio> #include <cstdlib> #include <iostream> using namespace std;

//square - returns the square of its argument

//doubleVar - the value to be squared

//returns - square of doubleVar double square(double doubleVar)

{

return doubleVar * doubleVar;

}

//sumSequence - accumulate the square of the number

//

entered at the keyboard into a sequence

//

until the user enters a negative number

double sumSequence(void)

{

 

// loop forever

double accumulator= 0.0;

for(;;)

 

{

 

// fetch another number

double dValue = 0;

cout << “Enter next number: “;

cin

>> dValue;

// if it’s negative...

if (dValue < 0)

{

// ...then exit from the loop

86

Part II: Becoming a Functional C++ Programmer

break;

}

//...otherwise calculate the square double value = square(dValue);

//now add the square to the

//accumulator

accumulator= accumulator + value;

}

// return the accumulated value return accumulator;

}

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

{

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

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

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

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

<<“negative numbers in a row\n”

<<endl;

//Continue to accumulate numbers...

double accumulatedValue; for(;;)

{

//sum a sequence of numbers entered from

//the keyboard

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

//terminate if the sequence is zero or negative if (accumulatedValue <= 0.0)

{

break;

}

//now output the accumulated result

cout << “\nThe total of the values squared is “

<<accumulatedValue

<<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;

}