Back to course sections
    Mark As Completed Discussion

    Functions and Modules

    Functions are blocks of code that perform a specific task. They allow you to break down complex problems into smaller, manageable parts. In C++, functions are defined with a return type, function name, and a set of parentheses that may contain parameters.

    TEXT/X-C++SRC
    1return_type function_name(parameters) {
    2  // code block
    3  return result;
    4}

    For example, let's consider a simple function that multiplies two numbers:

    TEXT/X-C++SRC
    1#include <iostream>
    2
    3using namespace std;
    4
    5// Function declaration
    6int multiply(int a, int b);
    7
    8int main() {
    9  // Function call
    10  int result = multiply(5, 7);
    11
    12  cout << "The result is: " << result << endl;
    13
    14  return 0;
    15}
    16
    17// Function definition
    18int multiply(int a, int b) {
    19  return a * b;
    20}

    In the above code:

    • We declare a function multiply with two parameters a and b of type int.
    • In the main function, we call the multiply function and store the result in the result variable.
    • The multiply function multiplies the two numbers and returns the result.
    • Finally, we print the result using the cout statement.

    Functions in C++ can also have a void return type, which means they don't return any value. These functions are used for performing actions or tasks without returning a result.

    Modules, on the other hand, are files that contain a collection of related functions and other programming elements. They help organize code, improve reusability, and make it easier to maintain and update programs. In C++, modules can be created by separating code into multiple files and using header files to provide function declarations.

    TEXT/X-C++SRC
    1// File: math_utils.h
    2
    3#ifndef MATH_UTILS_H
    4#define MATH_UTILS_H
    5
    6int multiply(int a, int b);
    7
    8#endif
    TEXT/X-C++SRC
    1// File: math_utils.cpp
    2
    3#include "math_utils.h"
    4
    5int multiply(int a, int b) {
    6  return a * b;
    7}

    In the above example, we have a header file math_utils.h that contains the declaration of the multiply function. The implementation of the function is then placed in a separate file math_utils.cpp. This separation of declaration and implementation allows us to use the multiply function in other files by including the math_utils.h header.

    By using functions and modules, you can create reusable code that can be used in multiple parts of your program, improving efficiency and making your programs easier to maintain.

    CPP
    OUTPUT
    :001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment