By Stephen R. Davis

Like so many things, functions in C++ are best understood by example. The following code snippet shows the simplest possible example of creating and invoking a function:

void someFunction()
{
    // do stuff
    return;
}
int main(int nNumberofArgs, char* pszArgs[])
{
    // do something
    // now invoke someFunction()
    someFunction();
    // keep going here once control returns
}

This example contains all the critical elements necessary to create and invoke a function:

  1. The declaration:

    The first thing is the declaration of the function: the name of the function with a type in front, followed by a set of open and closed parentheses. In this case, the name of the function is someFunction(), and its return type is void.

  2. The definition:

    The declaration of the function is followed by the definition of what it does, also called the body of the function. The body of a function always starts with an open brace and ends with a closed brace. The statements inside the body are just like those within a loop or an if statement.

  3. The return:

    The body of the function contains zero or more return statements. A return returns control to a point immediately after the point where the function was invoked. Control returns automatically if it ever reaches the final closed brace of the function body.

  4. The call:

    A function is called by invoking the name of the function followed by open and closed parentheses.

The flow of control is shown here.

image0.jpg

Functions often return a value to the caller. Sometimes this is a calculated value — a function like factorial() might return the factorial of a number. Sometimes this value is an indication of how things went — this is usually known as an error return. So the function might return a zero if everything went OK, and a non-zero if something went wrong during the execution of the function.

To return a value from a function, you need to make two changes:

  1. Replace void with the type of value you intend to return.

  2. Place the value you want the function to return after the keyword return. C++ does not allow you to return from a function by running into the final closed brace if the return type is other than void.

The keyword void is C++-ese for “nothing.” Thus a function declared with a return type of int returns an integer. A function declared with a return type of void returns nothing.