cpp-parametros-funciones

Function Parameters in C++

  • 3 min

In C++, parameters are defined variables that a function can receive when it is invoked.

Parameters make functions more flexible and reusable by allowing different data to be passed to the same function.

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

Parameters by Value and by Reference

Parameters by Value

Parameters by value pass a copy of the original value to the function. Any modification made to the parameter inside the function will not affect the original argument.

void funcion(int x)
{
    x = x * 2; // Modifies the local copy of x
}
Copied!

Parameters by Reference

Parameters by reference pass a reference to the original argument to the function. Any modification made to the parameter inside the function will affect the original argument.

void funcion(int &x)
{
    x = x * 2; // Modifies the original argument
}
Copied!

Parameters by Pointer

Parameters by pointer pass the memory address of the original argument to the function. The function can access and modify the value of the original argument through the pointer.

void funcion(int *ptr)
{
    *ptr = *ptr * 2; // Modifies the value pointed to by ptr
}
Copied!

Constant Parameters

Sometimes, we want a function to receive a parameter by reference (to avoid having to copy it), but we want to ensure the value is not modified. For this we use const.

#include <iostream>

void MostrarValor(const int &numero) {
    std::cout << "Value: " << numero << std::endl;
}

int main() {
    int valor = 5;
    MostrarValor(valor); // Displays 5
    return 0;
}
Copied!

Optional Parameters

In C++, optional parameters can be achieved using default values in the function declaration. If an argument is not passed when calling the function, the default value is used.

#include <iostream>

void Saludar(const std::string &nombre = "World") {
    std::cout << "Hello, " << nombre << "!" << std::endl;
}

int main() {
    Saludar();          // Displays "Hello, World!"
    Saludar("Luis");   // Displays "Hello, Luis!"
    return 0;
}
Copied!

Variadic Parameters

C++ supports variadic parameters using templates and the <cstdarg> library. Variadic parameters allow a function to accept a variable number of arguments.

#include <iostream>
#include <cstdarg>

void ImprimirNumeros(int cantidad, ...) {
    va_list args;
    va_start(args, cantidad);
    for (int i = 0; i < cantidad; ++i) {
        int numero = va_arg(args, int);
        std::cout << numero << " ";
    }
    va_end(args);
    std::cout << std::endl;
}

int main() {
    ImprimirNumeros(5, 1, 2, 3, 4, 5); // Displays 1 2 3 4 5
    return 0;
}
Copied!