Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

The Basics of Using Functions

I recommend the following approach for creating and calling user-defined functions:

  1. At the beginning of your program, declare the function.
  2. Somewhere in your program, define the function.
  3. Other functions can then call the function.

Step 1: Declare (Prototype) the Function

A function declaration (or prototype) provides type information only. It has this syntax:

return_type   function_name (argument_list);

The return_type is a data type indicating what kind of value the function returns (what it passes back). If the function does not return a value, use void.

The argument_list is a list of zero or more argument names—separated by commas if there are more than one—each preceded by the corresponding type. (Technically, you don’t need the argument names in a prototype, but it is a good programming practice.) For example, the following statement declares a function named avg, which takes two arguments of type double and returns a double value.

double avg(double x, double y);

The argument_list may be empty, which indicates that it takes no arguments.

Step 2: Define the Function

The function definition tells what the function does. It uses this syntax:

return_type   function_name (argument_list) {
    statements
 }

Most of this looks like a declaration. The only thing that’s different is that the semicolon is replaced by zero or more statements between two braces ({}). The braces are required no matter how few statements you have. For example:

double avg(double x, double y) {
    return (x + y) / 2;
}

The return statement causes immediate exit, and it specifies that the function returns the amount (x + y) / 2. Functions with no return value can still use the return statement but only to exit early.

return;

Step 3: Call the Function

Once a function is declared and defined, it can be used—or rather, called—any number of times, from any function. For example:

n = avg(9.5, 11.5);
n = avg(5, 25);
n = avg(27, 154.3);

A function call is an expression: As long as it returns a value other than void, it can be used inside a larger expression. For example:

z = x + y + avg(a, b) + 25.3;

When the function is called, the values specified in the function call are passed to the function arguments. Here’s how a call to the avg function works, with sample values 9.5 and 11.5 as input. These are passed to the function, as arguments. When the function returns, the value in this case is assigned to z.

Another call to the function might pass different values—in this case, 6 and 26. (Because these are integer values, they are implicitly converted, or promoted, to type double.)

Example 4.1. The avg() Function

This section shows a simple function call in the context of a complete program. It demonstrates all three steps: declare a function, define it, and call it.

avg.cpp

#include <iostream>
using namespace std;

// Function must be declared before being used.

double avg(double x, double y);

int main() {
    double a = 0.0;
    double b = 0.0;

    cout << "Enter first number and press ENTER: ";
    cin >> a;
    cout << "Enter second number and press ENTER: ";
    cin >> b;

    // Call the function avg().
    cout << "Average is: " << avg(a, b) << endl;
    system("PAUSE");
    return 0;
}

// Average-number function definition
//
double avg(double x, double y) {
    return (x + y)/2;
}

How It Works

overland_work_icon.jpg

This code is a very simple program, but it demonstrates the three steps I outlined earlier:

  1. Declare (that is, prototype) the function at the beginning of the program.
  2. Define the function somewhere in the program.
  3. Call the function from within another function (in this case, main).

Although function declarations (prototypes) can be placed anywhere in a program, you should almost always place them at the beginning. The general rule is that functions must be declared before being called. (They do not, however, have to be defined before being called, which makes it possible for two functions to call each other.)

double avg(double x, double y);

The function definition for the avg function is extremely simple, containing only one statement. In general, though, function definitions can contain as many statements as you want.

double avg(double x, double y) {
    return (x + y)/2;
}

The main function calls avg as part of a larger expression. The computed value (in this case, the average of the two inputs, a and b) is returned to this statement in main, which then prints the result.

cout << "Average is: " << avg(a, b) << endl;

Function Call a Function!

overland_variation_icon.jpg

A program can have any number of functions. For example, you could have two functions in addition to main, as in the following version of the program. Lines that are new or changed are in bold.

avg2.cpp

#include <iostream>
using namespace std;

// Functions must be declared before being used.

void print_results(double a, double b);
double avg(double x, double y);

int main() {
    double a = 0.0;
    double b = 0.0;

    cout << "Enter first number and press ENTER: ";
    cin >> a;
    cout << "Enter second number and press ENTER: ";
    cin >> b;

    // Call the function pr_results().
    print_results(a, b);

    system("PAUSE");
    return 0;
}

// print_results function definition
//
void print_results(double a, double b) {
    cout << "Average is: " << avg(a, b) << endl;
}
// Average-number function definition
//
double avg(double x, double y) {
    return (x + y)/2;
}

This version is a little less efficient, but it illustrates an important principle: You are not limited to only one or two functions. The program creates a flow of control as follows:

main() → print_results() → avg()

Exercises

overland_exercises_icon.jpg
  • Exercise 4.1.1. Write a program that defines and tests a factorial function. The factorial of a number is the product of all whole numbers from 1 to N. For example, the factorial of 5 is 1 * 2 * 3 * 4 * 5 = 120. (Hint: Use a for loop as described in Chapter 3.)
  • Exercise 4.1.2. Write a function named print_out that prints all the whole numbers from 1 to N. Test the function by placing it in a program that passes a number n to print_out, where this number is entered from the keyboard. The print_out function should have type void; it does not return a value. The function can be called with a simple statement:
    print_out(n);

Example 4.2. Prime-Number Function

Chapter 2 included an example that was actually useful: determining whether a specified number was a prime number. We can also write the prime-number test as a function and call it repeatedly.

The following program uses the prime-number example from Chapters 2 and 3 but places the relevant C++ statements into their own function, is_prime.

prime2.cpp

#include <iostream>
#include <cmath>
using namespace std;
// Function must be declared before being used.
bool prime(int n);

int main() {
    int i;

// Set up an infinite loop; break if user enters 0.
// Otherwise, evaluate n from prime-ness.

   while (true) {
     cout << "Enter num (0 = exit) and press ENTER: ";
     cin >> i;
     if (i == 0)            // If user entered 0, EXIT
        break;
     if (prime(i))                   // Call prime(i)
        cout << i << " is prime" << endl;
     else
        cout << i << " is not prime" << endl;
    }
    system("PAUSE");
    return 0;
}

// Prime-number function. Test divisors from
//  2 to sqrt of n. Return false if a divisor
//  found; otherwise, return true.

bool prime(int n) {
    int i;

    for (i = 2; i <= sqrt(n); i++) {
      if (n % i == 0)       // If i divides n evenly,
          return false;     //  n is not prime.
    }
    return true;   // If no divisor found, n is prime.
}

How It Works

overland_work_icon.jpg

As always, the program adheres to the pattern of 1) declaring function type information at the beginning of the program (prototyping the function), 2) defining the function somewhere in the program, and 3) calling the function.

The prototype says that the prime function takes an integer argument and returns a bool value, which will be either true or false. (Note: If you have a really old compiler, you may have to use the int type instead of bool.)

bool prime(int n);

The function definition is a variation on the prime-number code from Chapter 3, which used a for loop. If you compare the code here to Example 3.2 on page 75, you’ll see only a few differences.

bool prime(int n) {
    int i;

    for (i = 2; i <= sqrt(n); i++) {
        if (n % i == 0)     // If i divides n evenly,
            return false;         //  n is not prime.
    }
    return true;  // If no divisor found, return
true.
 }

Another difference is that instead of setting a Boolean variable, is_prime, this version returns a Boolean result. The logic here is as follows:

For all whole numbers from 2 to the square root of n,
If n is evenly divisible by the loop variable (i),
Return the value false immediately.

Remember that the modulus operator (%) carries out division and returns the remainder. If this remainder is 0, that means the second number divides the second evenly—in other words, it is a divisor or factor of the second number.

The action of the return statement here is key. This statement returns immediately—causing program execution to exit from the function and passing control back to main. There’s no need to use break to get out of the loop.

The loop in the main function calls the prime function. The use of a break statement here provides an exit mechanism, so the loop isn’t really infinite. As soon as the user enters 0, the loop terminates and the program ends. Here I’ve put the exit lines in bold.

    while (true) {
      cout << "Enter num (0 = exit) and press ENTER:
";
      cin >> i;
      if (i == 0)           // If user entered 0, EXIT
          break;
      if (prime(i))                   // Call prime(i)
         cout << i << " is prime" << endl;
      else
         cout << i << " is not prime" << endl;
     }

The rest of the loop calls the prime function and prints the result of the prime-number test. Note that the prime function, in this case, returns a true/false value, and so the call to prime(i) can be used as an if/else condition.

Exercises

overland_exercises_icon.jpg
  • Exercise 4.2.1. Optimize the prime-number function by calculating the square root of n only once during each function call. Declare a local variable sqrt_of_n of type double. (Hint: A variable is local if it is declared inside the function.) Then use this variable in the loop condition.
  • Exercise 4.2.2. Rewrite main so that it tests all the numbers from 2 to 20 and prints out the results, each on a separate line. (Hint: Use a for loop, with i running from 2 to 20.)
  • Exercise 4.2.3. Write a program that finds the first prime number greater than 1 billion (1,000,000,000).
  • Exercise 4.2.4. Write a program that lets the user enter any number n and then finds the first prime number larger than n.
  • + Share This
  • 🔖 Save To Your Account