Skip to content

Writing & Using

Functions are an essential part of writing organized and maintainable C++ programs. They allow you to delegate tasks, making your code easier to test, reuse, and extend. In this page, you’ll learn why functions are important, how to write and use them, and where they can be defined in your projects.

Functions are a key tool for improving the structure and efficiency of your programs. Using functions promotes cleaner, more modular code, making your programs more efficient and easier to debug.

  • Delegation of Tasks: Functions allow you to break down complex problems into smaller, manageable tasks. Each function performs a specific job, making your code easier to understand and maintain.

  • Ease of Testing: By isolating tasks into functions, you can test them independently to ensure they work correctly before integrating them into your program.

  • Reusability: Functions can be reused across different parts of your program or even in future projects, saving time and effort.

  • DRY Principle: Functions help you adhere to the Don’t Repeat Yourself (DRY) principle by consolidating repetitive code into a single function, reducing redundancy and the chance of errors.

Writing and using functions in C++ involves a few straightforward steps:

  1. Create the Prototype: Define the function’s return type, name, and parameter list at the beginning of your program or in a header file. This tells the compiler what the function looks like before its implementation.

    int GetMin(int, int);
  2. Write the Implementation: Provide the actual code for the function, specifying how it performs its task. This is usually done after the main function or in a separate source file.

    int GetMin(int x, int y) { return x <= y ? x : y; }
  3. Test It (Call It): Call the function from your main function or another part of your program to test its behavior and ensure it works as expected.

    driver.cc
    // Copyright 2024 CSCE240
    #include <iostream>
    using std::cout;
    using std::endl;
    // Function to find the smallest value
    int GetMin(int, int);
    int main() {
    const bool test1 = GetMin(1, 2) == 1;
    const bool test2 = GetMin(3, -3) == -3;
    const bool test3 = GetMin(4, 4) == 4;
    cout << "Test 1: " << test1 << endl;
    cout << "Test 2: " << test2 << endl;
    cout << "Test 3: " << test3 << endl;
    return 0;
    }
    int GetMin(int x, int y) { return x <= y ? x : y; }

Functions can be written in various locations depending on the structure of your program and how you plan to use them.

In the Driver with main: When starting out, you’ll typically write your functions in the same source file as your main function. This keeps everything in one place, making it easier to learn and test.

In Separate Source Files: Functions can also be written in separate source files without a main function. These files can be compiled individually and linked into larger projects. This approach is useful for organizing code in larger programs.

In Header Files: Functions can be declared in header files and implemented in source files. This allows you to reuse them across multiple projects by simply including the header file.

A function’s prototype is a declaration that specifies the structure of a function, including its name, return type, and parameter list. It serves as a promise to the compiler that the function will be implemented later in the program.

  • Single Statement: A prototype is a single statement and must end with a semicolon (;). For example:
int Multiply(int x, int y);
  • Optional Parameter Names: Naming the parameters in the prototype is optional, but including them can improve readability:
int Add(int, int); // Valid
int Add(int a, int b); // Also valid and more descriptive

Placement: Prototypes should not appear inside the body of any other function. They must also precede all calls to the function, either at the top of the source file or in a header file.

The implementation of a function provides the full definition, including how it performs its task. It consists of two main parts:

  1. The Function Header: Specifies the return type, function name, and parameter list.

  2. The Function Body: Contains the C++ commands enclosed in braces ({}) that define the function’s behavior.

  • Named Parameters: Parameters must be named in the function header so they can be referenced within the function body. These parameters are local to the function, meaning they cannot be accessed outside of it.
int Add(int a, int b) { // 'a' and 'b' are local to this function
return a + b;
}
  • No Semicolon: There is no semicolon between the function header and the opening brace of the body.

  • Separate Implementations: Each function must be implemented independently. One function cannot be implemented inside the body of another function.

Lets create a calculator program that allows a user to add, subtract, multiply, and divide numbers they enter.

    • We’ll create a document called driver.cc, copyright the document, and create our main function.

    • We want to print to the terminal and take user input so we’ll #include the <iostream> class and use the cin, cout, and endl objects

    driver.cc
    // Copyright 2024 CSCE240
    #include <iostream>
    using std::cin;
    using std::cout;
    using std::endl;
    int main() {
    return 0;
    }
    • We want to greet the user when the program is first run.

    • Lets give the user the ability to add, subtract, multiply, divide, and square integers they enter.

    driver.cc
    // Copyright 2024 CSCE240
    #include <iostream>
    using std::cin;
    using std::cout;
    using std::endl;
    void Greet();
    int Add(int x, int y);
    int Subtract(int x, int y);
    int Multiply(int x, int y);
    double Divide(double num, double denom);
    int Square(int x);
    int main() {
    return 0;
    }
    • Below our main function, we’ll code the implementation of our functions.

    • We’ll assume for this exercise that user input is ALWAYS correct.

    driver.cc
    void Greet() {
    cout << "------------------------------------" << endl;
    cout << "Welcome to the CSCE240 Calculator!!!" << endl;
    cout << "------------------------------------\n" << endl;
    }
    int Add(int x, int y) { return x + y; }
    int Subtract(int x, int y) { return x - y; }
    int Multiply(int x, int y) { return x * y; }
    double Divide(double num, double denom) {
    if (num == 0 || denom == 0) {
    return 0;
    } else {
    return num / denom;
    }
    }
    int Square(int x) { return x * x; }
    • Lets write a couple of tests in our main function to check the implementation of our functions.

    • Then we’ll check our styles and run the program.

    driver.cc
    int main() {
    Greet();
    bool add_test = Add(4, 5) == 9;
    bool subtract_test = Subtract(0, 10) == -10;
    bool multiply_test = Multiply(3, 4) == 12;
    bool divide_test = Divide(1, 0) == 0;
    bool square_test = Square(5) == 25;
    cout << "Add: " << add_test << "\n"
    << "Subtract: " << subtract_test << "\n"
    << "Multiply: " << multiply_test << "\n"
    << "Divide: " << divide_test << "\n"
    << "Square: " << square_test << endl;
    return 0;
    }
    • Divide() is a little different than the rest of the functions, so we’ll call it a couple of times to see its output

    • Finally we’ll recompile our program and run it to see the results.

    driver.cc
    int main() {
    cout << Divide(1, 2) << endl;
    cout << Divide(0, 2) << endl;
    cout << Divide(10, 5) << endl;
    cout << Divide(-1, 1) << endl;
    return 0;
    }
    • We need to print a message for the user to notify them which options they have.

    • Lets declare another function prototype and add it to the others.

    driver.cc
    void FrontEnd();
    • Now we need to write its implementation.
    driver.cc
    void FrontEnd() {
    cout << "Enter 1: To Add" << endl;
    cout << "Enter 2: To Subtract" << endl;
    cout << "Enter 3: To Multiply" << endl;
    cout << "Enter 4: To Divide" << endl;
    cout << "Enter 5: To Square" << endl;
    cout << "Enter 0: To Quit" << endl;
    }
    • This FrontEnd should remind you of the many programs written in CSCE146. What we are going to do is:

      1. Wrap our code in a while loop.

      2. Print options to the user -> await input.

      3. Direct that input to match a case in a switch statement.

      4. Get the required input to fulfill the requirements of that operation.

      5. Print an output.

      6. Repeat until the user quits the program.

    • This is the final version of our main function:

    driver.cc
    int main() {
    Greet();
    bool run_program = true;
    while (run_program) {
    FrontEnd();
    int input;
    cin >> input;
    switch (input) {
    case 0:
    run_program = false;
    break;
    case 1: // Add
    cout << "Enter the first integer to add: " << endl;
    int first_add;
    cin >> first_add;
    cout << "Enter the second integer to add: " << endl;
    int second_add;
    cin >> second_add;
    cout << first_add << " + " << second_add << " = "
    << Add(first_add, second_add) << "\n"
    << endl;
    break;
    case 2: // Subtract
    cout << "Enter the first integer to subtract: " << endl;
    int first_sub;
    cin >> first_sub;
    cout << "Enter the second integer to subtract: " << endl;
    int second_sub;
    cin >> second_sub;
    cout << first_sub << " - " << second_sub << " = "
    << Subtract(first_sub, second_sub) << "\n"
    << endl;
    break;
    case 3: // Multiply
    cout << "Enter the first integer to multiply: " << endl;
    int first_mul;
    cin >> first_mul;
    cout << "Enter the second integer to multiply: " << endl;
    int second_mul;
    cin >> second_mul;
    cout << first_mul << " * " << second_mul << " = "
    << Multiply(first_mul, second_mul) << "\n"
    << endl;
    break;
    case 4: // Divide
    cout << "Enter the numerator: " << endl;
    int num;
    cin >> num;
    cout << "Enter the denominator: " << endl;
    int denom;
    cin >> denom;
    cout << num << " / " << denom << " = " << Divide(num, denom) << "\n"
    << endl;
    break;
    case 5: // Square
    cout << "Enter the integer you would like to square: " << endl;
    int square;
    cin >> square;
    cout << square << "^2 = " << Square(square) << "\n" << endl;
    break;
    default:
    cout << "Please enter an integer for the available options\n" << endl;
    }
    }
    cout << "Calculator powering off..." << endl;
    return 0;
    }
    • Finally we can run our program and test different inputs to see how it runs.

    • Instead of showing one long terminal log, I’ve parsed the output for each test:

    Terminal window
    cpplint driver.cc
    Done processing driver.cc
    g++ -Wall -std=c++17 driver.cc
    ./a.out
    Terminal window
    ------------------------------------
    Welcome to the CSCE240 Calculator!!!
    ------------------------------------
    Enter 1: To Add
    Enter 2: To Subtract
    Enter 3: To Multiply
    Enter 4: To Divide
    Enter 5: To Square
    Enter 0: To Quit
    9
    Please enter an integer for the available options
    Terminal window
    Enter 1: To Add
    Enter 2: To Subtract
    Enter 3: To Multiply
    Enter 4: To Divide
    Enter 5: To Square
    Enter 0: To Quit
    1
    Enter the first integer to add:
    5
    Enter the second integer to add:
    5
    5 + 5 = 10
    Terminal window
    Enter 1: To Add
    Enter 2: To Subtract
    Enter 3: To Multiply
    Enter 4: To Divide
    Enter 5: To Square
    Enter 0: To Quit
    2
    Enter the first integer to subtract:
    5
    Enter the second integer to subtract:
    10
    5 - 10 = -5
    Terminal window
    Enter 1: To Add
    Enter 2: To Subtract
    Enter 3: To Multiply
    Enter 4: To Divide
    Enter 5: To Square
    Enter 0: To Quit
    3
    Enter the first integer to multiply:
    7
    Enter the second integer to multiply:
    7
    7 * 7 = 49
    Terminal window
    Enter 1: To Add
    Enter 2: To Subtract
    Enter 3: To Multiply
    Enter 4: To Divide
    Enter 5: To Square
    Enter 0: To Quit
    4
    Enter the numerator:
    100
    Enter the denominator:
    20
    100 / 20 = 5
    Terminal window
    Enter 1: To Add
    Enter 2: To Subtract
    Enter 3: To Multiply
    Enter 4: To Divide
    Enter 5: To Square
    Enter 0: To Quit
    5
    Enter the integer you would like to square:
    9
    9^2 = 81
    Terminal window
    Enter 1: To Add
    Enter 2: To Subtract
    Enter 3: To Multiply
    Enter 4: To Divide
    Enter 5: To Square
    Enter 0: To Quit
    0
    Calculator powering off...