Functions

This tutorial attempts to start at the very beginning, and assumes that you know only the basics of C++ (types, expressions, etc).

Motivation for Functions

By now you've probably noticed that there are some things you have to do in just about every program. The obvious example is getting a valid integer from the user: you have to check if they actually entered a number, if it's within the correct boundaries, and so on. There are also things that you have to do more than once within a single program, but at different places (so you can't just use a loop). For example, you might have a program that has to calculate the distance between two points at various spots in the program.

Wouldn't it be nice if there were an easy way to reuse code without copy-pasting all the time?

Abstract Concept of Functions

If programs are like people, functions are sort of like robots. A function's not a program, because it can't do anything by itself - it needs a real program to tell it what to do. Each function can do one thing, and you have to provide it with exactly what it needs in order to do its job.

In order to use (or write) a function, you have to know (or decide) three things:

Example 1: the job of a GetInteger function is to get a valid integer from the user. In order to do that, it needs a question to ask the user and (possibly) a range of values that the answer is allowed to fall into. When it's done getting the integer, it brings that integer back to the main program.

Example 2: the job of a Distance function is to calculate the distance between two points. To do the calculation, it needs to know the coordinates of the points. After it finishes, it brings back the distance (which is a real number).

A function doesn't need to bring back (return) anything. (For example, you could have a robot whose job is to assemble an object but leave it where it was - then, all it needs to do when it's done is tell you it's done.)

Example 3: the job of a DisplayMoney function is to print a number to the screen in a money format (i.e., 20 could be displayed as $20.00). So it needs to be given a number to display, but doesn't need to bring anything back.

So a function is a reusable piece of code that accepts some input, does some work with it, and (possibly) brings back some information.

Basics of Functions in C++

A C++ program that uses functions has the following order:

Prototypes

A robot that does some job should have a sign (or instruction book, whatever) that tells what it does and how to make it work. This is the same way with functions. Each function has a corresponding line of code, called a prototype, that gives us the three pieces of information that we need to use it. A prototype has the general form
returntype FunctionName (parameters);
The prototype for the Distance function might look like this:
double Distance ( int x1, int y1, int x2, int y2 );
double is the return type: the C++ type of what the function returns (brings back). As discussed in the previous section, a function doesn't have to return anything. If this is the case, the return type is void.
Distance is the function name, which should be reasonably short but give us an idea of what the function does.
The part in the parentheses is called the parameter list, which contains the formal parameters of the function. The parameter list is the list of things the function needs in order to do its job. (In this case, (x1,y1) and (x2,y2) are the coordinates of the points between which the function finds the distance.) Each parameter (item in the list) must have a specified type (int in this case) so that C++ knows what to expect. Normally each parameter is also given a name in the prototype, although it's not required.
The prototype ends with a semicolon.

Function Calls

In your main program, you use the function by calling it. (This is like selecting a robot, feeding it its information, and sending it on its way.) In the following code, the function call for the Distance function is in red; the rest of the code is in black.
.
.
.
//create point p1 with x,y-coordinates (5,0)
int p1_x = 5;
int p1_y = 0;

//create point p2 with x,y-coordinates (5,5)
int p2_x = 5;
int p2_y = 5;

//calculate distance between p1 and p2
double d = Distance(p1_x, p1_y, p2_x, p2_y);
.
.
.

Notice that it looks like I assigned the function to a variable(d). This is similar to writing int a = 5 + 7; - the expression on the right hand side is evaluated, and the resultant value is assigned to the variable on the left hand side. A function essentially evaluates to its return value. This allows me to put the result of a function into a variable. Realize that a function with a void return type does not return anything, so I can't assign its result to a variable.

A function call can go anywhere a normal expression can. For example, I can write

double d_and_then_some = Distance(p1_x, p1_y, p2_x, p2_y) + 3;

I can also print the result to the screen:

cout << "Distance is " << Distance(p1_x, p1_y, p2_x, p2_y) << endl;
Since a function with a void return type doesn't return anything, I can't print its result to the screen. (It's possible that the function itself prints to the screen; for example, the DisplayMoney function.)

A function call may occur in any piece of code, including in a function.

Function Definitions

Writing a function definition is like building or programming a robot. You write the definition once, and then you can use it as often as you'd like.

As stated before, function definitions go after main. They take the form

returntype FunctionName(parameters)
{
   //code
}
Notice that the first line of the function definition is exactly like the prototype, except without the ending semicolon. This is important: if your function definition doesn't match the prototype, you'll get a compilation error.

Here's a sample definition for the SquareIt function:

//This function accepts a number and returns its square.
//(Obviously this isn't a function you'd actually write; it's just an example.)
double SquareIt(double x)
{
   double square = x * x;
   return square;
}
Notice that I declared a new variable inside the function. That variable, square exists only inside the function: no other functions or programs can get to it. Of course it's a bit wasteful to declare a new variable here. A better implementation would be:
double SquareIt(double x)
{
   return x * x;
}
This function consists only of a return statement, which is perfectly fine. Notice that I can return an entire expression; C++ will evaluate it before sending its value back to where the function was called from.


More will be added to this tutorial as I find time. I hope it's been helpful to you, and if you have any problems, questions, or corrections please contact me.


Back to the Main Page