Language: EN

cpp-parametros-funciones

Function Parameters in C++

In C++, parameters are variables defined 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.

Pass-by-value and pass-by-reference parameters

Pass-by-value parameters

Pass-by-value parameters pass a copy of the original value to the function. Any modification made to the parameter within the function will not affect the original argument.

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

Pass-by-reference parameters

Pass-by-reference parameters pass a reference to the original argument to the function. Any modification made to the parameter within the function will affect the original argument.

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

Pointer parameters

Pointer parameters 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
}

Constant parameters

Sometimes, we want a function to receive a parameter by reference (to avoid copying it), but we want to ensure that 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;
}

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;
}

Variadic parameters

C++ supports variadic parameters through the use of 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;
}