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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020