cpp-que-son-las-funciones

What are and how to use functions in C++

  • 6 min

In C++, functions are reusable blocks of code that perform specific tasks and can be invoked from other parts of the program.

Functions allow dividing code into more manageable fragments (this allows us to create more reusable code and improve the program’s readability and maintainability).

If you want to learn more, check out the Introduction to Programming Course

What is a function

A function in C++ is a set of instructions that performs a specific task. A function can be defined to receive certain parameters, process this data, and return a result if necessary. The basic structure of a function in C++ is as follows:

return_type function_name(parameter_type parameter1, parameter_type parameter2, ...)
{
    // Function code
    return return_value; // Optional
}
Copied!
  • Return type: This is the type of value the function returns. It can be any data type, such as int, double, char, etc. If the function does not return any value, void is used.
  • Function name: This is the function’s identifier. It must be unique within the scope where it is defined.
  • Parameter list: These are variables passed to the function so it can operate with this data (Parameters are optional, and a function may have no parameters)
  • Function code: This is the block of code that executes when the function is called.
  • Return value: This is the result the function returns, if applicable. The return statement is used to return a value.

Basic example

Let’s look at a basic example of a function in C++ that adds two numbers:

#include <iostream>

int Add(int num1, int num2) {
    return num1 + num2;
}

int main() {
    int result = Add(5, 3);
    std::cout << "The sum is: " << result << std::endl;
    return 0;
}
Copied!

In this example:

  • The Add function takes two parameters (num1 and num2), performs the addition operation, and returns the result.
  • In main, the Add function is called with the values 5 and 3, and the result 8 is printed to the console.

Calling functions

To call a function, you simply use its name followed by parentheses containing the necessary arguments (if any). Here is an example of calling the Add function:

int result = Add(5, 3);
Copied!

This line,

  • Calls the Add function with the values 5 and 3
  • Stores the result in the variable result

Parameters

Functions in C++ can accept parameters, which are values passed to the function for it to process. These parameters are defined in the function declaration and are used inside the function to perform calculations or manipulations.

For example, the following function calculates the area of a rectangle given its width and height:

double CalculateRectangleArea(double width, double height) {
    return width * height;
}
Copied!

In this function, width and height are the parameters used to calculate the rectangle’s area.

Return value

Functions can return a value using the return keyword. The type of value returned must match the return type specified in the function declaration.

For example, the following function calculates the area of a circle given its radius:

#include <cmath> // For the constant M_PI

double CalculateCircleArea(double radius) {
    return M_PI * radius * radius;
}
Copied!

The CalculateCircleArea function returns the area of the circle using the M_PI constant from the cmath library.

Functions without return

If a function does not return any value, the return type void is used. These functions are generally used to perform actions without needing to return a result.

For example, a function that prints a message to the console:

void PrintMessage(const std::string& message) {
    std::cout << message << std::endl;
}
Copied!

Here, PrintMessage does not return any value; it simply prints the provided message.

Inline functions

inline functions suggest to the compiler to expand the function’s code at the call site (instead of making a normal function call). This can improve performance for small, frequently called functions.

inline int sum(int a, int b) {
    return a + b;
}
Copied!

inline is a “suggestion” to the compiler. Ultimately, the compiler may decide to ignore it, or apply it to functions (even without us specifying it)

Recursive functions

A function is recursive if it calls itself. Recursion is useful for solving problems that can be divided into smaller subproblems of the same type.

#include <iostream>

int factorial(int n) {
    if (n <= 1) {
        return 1;
    } else {
        return n * factorial(n - 1);
    }
}

int main() {
    int number = 5;
    std::cout << "The factorial of " << number << " is " << factorial(number) << std::endl;
    return 0;
}
Copied!

Practical examples

These examples show how to define and use functions in C++. This does not mean they are always the best way to solve all problems; in some cases, there may be more suitable solutions.