Functions
Because functions are the modules from which C++ programs are built and because they are essential to C++ OOP definitions, you should become thoroughly familiar with them. Some aspects of functions are advanced topics, so the main discussion of functions comes later, in Chapter 7, “Functions: C++’s Programming Modules,” and Chapter 8, “Adventures in Functions.” However, if we deal now with some basic characteristics of functions, you’ll be more at ease and more practiced with functions later. The rest of this chapter introduces you to these function basics.
C++ functions come in two varieties: those with return values and those without them. You can find examples of each kind in the standard C++ library of functions, and you can create your own functions of each type. Let’s look at a library function that has a return value and then examine how you can write your own simple functions.
Using a Function That Has a Return Value
A function that has a return value produces a value that you can assign to a variable or use in some other expression. For example, the standard C/C++ library includes a function called sqrt() that returns the square root of a number. Suppose you want to calculate the square root of 6.25 and assign it to the variable x. You can use the following statement in your program:
x = sqrt(6.25); // returns the value 2.5 and assigns it to x
The expression sqrt(6.25) invokes, or calls, the sqrt() function. The expression sqrt(6.25) is termed a function call, the invoked function is termed the called function, and the function containing the function call is termed the calling function (see Figure 2.6).
Figure 2.6 Calling a function.
The value in the parentheses (6.25, in this example) is information that is sent to the function; it is said to be passed to the function. A value that is sent to a function this way is called an argument or parameter (see Figure 2.7). The sqrt() function calculates the answer to be 2.5 and sends that value back to the calling function; the value sent back is termed the return value of the function. Think of the return value as what is substituted for the function call in the statement after the function finishes its job. Thus, this example assigns the return value to the variable x. In short, an argument is information sent to the function, and the return value is a value sent back from the function.
Figure 2.7 Function call syntax.
That’s practically all there is to it, except that before the C++ compiler uses a function, it must know what kind of arguments the function uses and what kind of return value it has. That is, does the function return an integer? a character? a number with a decimal fraction? a guilty verdict? or something else? If it lacks this information, the compiler won’t know how to interpret the return value. The C++ way to convey this information is to use a function prototype statement.
A function prototype does for functions what a variable declaration does for variables: It tells what types are involved. For example, the C++ library defines the sqrt() function to take a number with (potentially) a fractional part (like 6.25) as an argument and to return a number of the same type. Some languages refer to such numbers as real numbers, but the name C++ uses for this type is double. (You’ll see more of double in Chapter 3.) The function prototype for sqrt() looks like this:
double sqrt(double); // function prototype
The initial double means sqrt() returns a type double value. The double in the parentheses means sqrt() requires a double argument. So this prototype describes sqrt() exactly as used in the following code:
double x; // declare x as a type double variable x = sqrt(6.25);
The terminating semicolon in the prototype identifies it as a statement and thus makes it a prototype instead of a function header. If you omit the semicolon, the compiler interprets the line as a function header and expects you to follow it with a function body that defines the function.
When you use sqrt() in a program, you must also provide the prototype. You can do this in either of two ways:
- You can type the function prototype into your source code file yourself.
- You can include the cmath (math.h on older systems) header file, which has the prototype in it.
The second way is better because the header file is even more likely than you to get the prototype right. Every function in the C++ library has a prototype in one or more header files. Just check the function description in your manual or with online help, if you have it, and the description tells you which header file to use. For example, the description of the sqrt() function should tell you to use the cmath header file. (Again, you might have to use the older math.h header file, which works for both C and C++ programs.)
Don’t confuse the function prototype with the function definition. The prototype, as you’ve seen, only describes the function interface. That is, it describes the information sent to the function and the information sent back. The definition, however, includes the code for the function’s workings—for example, the code for calculating the square root of a number. C and C++ divide these two features—prototype and definition—for library functions. The library files contain the compiled code for the functions, whereas the header files contain the prototypes.
You should place a function prototype ahead of where you first use the function. The usual practice is to place prototypes just before the definition of the main() function. Listing 2.4 demonstrates the use of the library function sqrt(); it provides a prototype by including the cmath file.
Listing 2.4. sqrt.cpp
// sqrt.cpp -- using the sqrt() function #include <iostream> #include <cmath> // or math.h int main() { using namespace std; double area; cout << "Enter the floor area, in square feet, of your home: "; cin >> area; double side; side = sqrt(area); cout << "That's the equivalent of a square " << side << " feet to the side." << endl; cout << "How fascinating!" << endl; return 0; }
Here’s a sample run of the program in Listing 2.4:
Enter the floor area, in square feet, of your home: 1536 That's the equivalent of a square 39.1918 feet to the side. How fascinating!
Because sqrt() works with type double values, the example makes the variables that type. Note that you declare a type double variable by using the same form, or syntax, as when you declare a type int variable:
type-name variable-name;
Type double allows the variables area and side to hold values with decimal fractions, such as 1536.0 and 39.1918. An apparent integer, such as 1536, is stored as a real value with a decimal fraction part of .0 when stored in a type double variable. As you’ll see in Chapter 3, type double encompasses a much greater range of values than type int.
C++ allows you to declare new variables anywhere in a program, so sqrt.cpp didn’t declare side until just before using it. C++ also allows you to assign a value to a variable when you create it, so you could also have done this:
double side = sqrt(area);
You’ll learn more about this process, called initialization, in Chapter 3.
Note that cin knows how to convert information from the input stream to type double, and cout knows how to insert type double into the output stream. As noted earlier, these objects are smart.
Function Variations
Some functions require more than one item of information. These functions use multiple arguments separated by commas. For example, the math function pow() takes two arguments and returns a value equal to the first argument raised to the power given by the second argument. It has this prototype:
double pow(double, double); // prototype of a function with two arguments
If, say, you wanted to find 58 (5 to the eighth power), you would use the function like this:
answer = pow(5.0, 8.0); // function call with a list of arguments
Other functions take no arguments. For example, one of the C libraries (the one associated with the cstdlib or the stdlib.h header file) has a rand() function that has no arguments and that returns a random integer. Its prototype looks like this:
int rand(void); // prototype of a function that takes no arguments
The keyword void explicitly indicates that the function takes no arguments. If you omit void and leave the parentheses empty, C++ interprets this as an implicit declaration that there are no arguments. You could use the function this way:
myGuess = rand(); // function call with no arguments
Note that unlike some computer languages, in C++ you must use the parentheses in the function call even if there are no arguments.
There also are functions that have no return value. For example, suppose you wrote a function that displayed a number in dollars-and-cents format. You could send to it an argument of, say, 23.5, and it would display $23.50 onscreen. Because this function sends a value to the screen instead of to the calling program, it doesn’t require a return value. You indicate this in the prototype by using the keyword void for the return type:
void bucks(double); // prototype for function with no return value
Because bucks() doesn’t return a value, you can’t use this function as part of an assignment statement or of some other expression. Instead, you have a pure function call statement:
bucks(1234.56); // function call, no return value
Some languages reserve the term function for functions with return values and use the terms procedure or subroutine for those without return values, but C++, like C, uses the term function for both variations.
User-Defined Functions
The standard C library provides more than 140 predefined functions. If one fits your needs, by all means use it. But often you have to write your own, particularly when you design classes. Anyway, it’s fun to design your own functions, so now let’s examine that process. You’ve already used several user-defined functions, and they have all been named main(). Every C++ program must have a main() function, which the user must define. Suppose you want to add a second user-defined function. Just as with a library function, you can call a user-defined function by using its name. And, as with a library function, you must provide a function prototype before using the function, which you typically do by placing the prototype above the main() definition. But now you, not the library vendor, must provide source code for the new function. The simplest way is to place the code in the same file after the code for main(). Listing 2.5 illustrates these elements.
Listing 2.5. ourfunc.cpp
// ourfunc.cpp -- defining your own function #include <iostream> void simon(int); // function prototype for simon() int main() { using namespace std; simon(3); // call the simon() function cout << "Pick an integer: "; int count; cin >> count; simon(count); // call it again cout << "Done!" << endl; return 0; } void simon(int n) // define the simon() function { using namespace std; cout << "Simon says touch your toes " << n << " times." << endl; } // void functions don't need return statements
The main() function calls the simon() function twice, once with an argument of 3 and once with a variable argument count. In between, the user enters an integer that’s used to set the value of count. The example doesn’t use a newline character in the cout prompting message. This results in the user input appearing on the same line as the prompt. Here is a sample run of the program in Listing 2.5:
Simon says touch your toes 3 times. Pick an integer: 512 Simon says touch your toes 512 times. Done!
Function Form
The definition for the simon() function in Listing 2.5 follows the same general form as the definition for main(). First, there is a function header. Then, enclosed in braces, comes the function body. You can generalize the form for a function definition as follows:
type functionname(argumentlist) { statements }
Note that the source code that defines simon() follows the closing brace of main(). Like C, and unlike Pascal, C++ does not allow you to embed one function definition inside another. Each function definition stands separately from all others; all functions are created equal (see Figure 2.8).
Figure 2.8 Function definitions occur sequentially in a file.
Function Headers
The simon() function in Listing 2.5 has this header:
void simon(int n)
The initial void means that simon() has no return value. So calling simon() doesn’t produce a number that you can assign to a variable in main(). Thus, the first function call looks like this:
simon(3); // ok for void functions
Because poor simon() lacks a return value, you can’t use it this way:
simple = simon(3); // not allowed for void functions
The int n within the parentheses means that you are expected to use simon() with a single argument of type int. The n is a new variable assigned the value passed during a function call. Thus, the following function call assigns the value 3 to the n variable defined in the simon() header:
simon(3);
When the cout statement in the function body uses n, it uses the value passed in the function call. That’s why simon(3) displays a 3 in its output. The call to simon(count) in the sample run causes the function to display 512 because that was the value entered for count. In short, the header for simon() tells you that this function takes a single type int argument and that it doesn’t have a return value.
Let’s review main()’s function header:
int main()
The initial int means that main() returns an integer value. The empty parentheses (which optionally could contain void) means that main() has no arguments. Functions that have return values should use the keyword return to provide the return value and to terminate the function. That’s why you’ve been using the following statement at the end of main():
return 0;
This is logically consistent: main() is supposed to return a type int value, and you have it return the integer 0. But, you might wonder, to what are you returning a value? After all, nowhere in any of your programs have you seen anything calling main():
squeeze = main(); // absent from our programs
The answer is that you can think of your computer’s operating system (Unix, say, or Windows) as calling your program. So main()’s return value is returned not to another part of the program but to the operating system. Many operating systems can use the program’s return value. For example, Unix shell scripts and Window’s command-line interface batch files can be designed to run programs and test their return values, usually called exit values. The normal convention is that an exit value of zero means the program ran successfully, whereas a nonzero value means there was a problem. Thus, you can design a C++ program to return a nonzero value if, say, it fails to open a file. You can then design a shell script or batch file to run that program and to take some alternative action if the program signals failure.
Using a User-Defined Function That Has a Return Value
Let’s go one step further and write a function that uses the return statement. The main() function already illustrates the plan for a function with a return value: Give the return type in the function header and use return at the end of the function body. You can use this form to solve a weighty problem for those visiting the United Kingdom. In the United Kingdom, many bathroom scales are calibrated in stone instead of in U.S. pounds or international kilograms. The word stone is both singular and plural in this context. (The English language does lack the internal consistency of, say, C++.) One stone is 14 pounds, and the program in Listing 2.6 uses a function to make this conversion.
Listing 2.6. convert.cpp
// convert.cpp -- converts stone to pounds #include <iostream> int stonetolb(int); // function prototype int main() { using namespace std; int stone; cout << "Enter the weight in stone: "; cin >> stone; int pounds = stonetolb(stone); cout << stone << " stone = "; cout << pounds << " pounds." << endl; return 0; } int stonetolb(int sts) { return 14 * sts; }
Here’s a sample run of the program in Listing 2.6:
Enter the weight in stone: 15 15 stone = 210 pounds.
In main(), the program uses cin to provide a value for the integer variable stone. This value is passed to the stonetolb() function as an argument and is assigned to the variable sts in that function. stonetolb() then uses the return keyword to return the value of 14 * sts to main(). This illustrates that you aren’t limited to following return with a simple number. Here, by using a more complex expression, you avoid the bother of having to create a new variable to which to assign the value before returning it. The program calculates the value of that expression (210 in this example) and returns the resulting value. If returning the value of an expression bothers you, you can take the longer route:
int stonetolb(int sts) { int pounds = 14 * sts; return pounds; }
Both versions produce the same result. The second version, because it separates the computation process from the return process, is easier to read and modify.
In general, you can use a function with a return value wherever you would use a simple constant of the same type. For example, stonetolb() returns a type int value. This means you can use the function in the following ways:
int aunt = stonetolb(20); int aunts = aunt + stonetolb(10); cout << "Ferdie weighs " << stonetolb(16) << " pounds." << endl;
In each case, the program calculates the return value and then uses that number in these statements.
As these examples show, the function prototype describes the function interface—that is, how the function interacts with the rest of the program. The argument list shows what sort of information goes into the function, and the function type shows the type of value returned. Programmers sometimes describe functions as black boxes (a term from electronics) specified by the flow of information into and out of them. The function prototype perfectly portrays that point of view (see Figure 2.9).
Figure 2.9 The function prototype and the function as a black box.
The stonetolb() function is short and simple, yet it embodies a full range of functional features:
- It has a header and a body.
- It accepts an argument.
- It returns a value.
- It requires a prototype.
Consider stonetolb() as a standard form for function design. You’ll further explore functions in Chapters 7 and 8. In the meantime, the material in this chapter should give you a good feel for how functions work and how they fit into C++.
Placing the using Directive in Multifunction Programs
Notice that Listing 2.5 places a using directive in each of the two functions:
using namespace std;
This is because each function uses cout and thus needs access to the cout definition from the std namespace.
There’s another way to make the std namespace available to both functions in Listing 2.5, and that’s to place the directive outside and above both functions:
// ourfunc1.cpp -- repositioning the using directive #include <iostream> using namespace std; // affects all function definitions in this file void simon(int); int main() { simon(3); cout << "Pick an integer: "; int count; cin >> count; simon(count); cout << "Done!" << endl; return 0; } void simon(int n) { cout << "Simon says touch your toes " << n << " times." << endl; }
The current prevalent philosophy is that it’s preferable to be more discriminating and limit access to the std namespace to only those functions that need access. For example, in Listing 2.6, only main() uses cout, so there is no need to make the std namespace available to the stonetolb() function. Thus, the using directive is placed inside the main() function only, limiting std namespace access to just that function.
In summary, you have several choices for making std namespace elements available to a program. Here are some:
- You can place the following above the function definitions in a file, making all the contents of the std namespace available to every function in the file:
using namespace std;
- You can place the following in a specific function definition, making all the contents of the std namespace available to that specific function:
using namespace std;
- Instead of using
using namespace std;
you can place using declarations like the following in a specific function definition and make a particular element, such as cout, available to that function:
using std::cout;
- You can omit the using directives and declarations entirely and use the std:: prefix whenever you use elements from the std namespace:
std::cout << "I'm using cout and endl from the std namespace" << std::endl;