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 the passing of different data to the same function.

Pass-by-value and Pass-by-reference

Pass-by-value

When we pass parameters by value, a copy of the value is passed to the function. This means that any modification within the function will not affect the original value in the place where the function was called.

#include <iostream>

void Increment(int number) {
    number++;
    std::cout << "Inside the function: " << number << std::endl; // Shows 6
}

int main() {
    int value = 5;
    Increment(value);
    std::cout << "Outside the function: " << value << std::endl; // Shows 5
    return 0;
}

Pass-by-reference

Passing parameters by reference allows the function to modify the original value of the passed variable. This is achieved by using the & operator in the parameter declaration.

#include <iostream>

void Increment(int &number) {
    number++;
}

int main() {
    int value = 5;
    Increment(value);
    std::cout << "Outside the function: " << value << std::endl; // Shows 6
    return 0;
}

Constant Parameters

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

#include <iostream>

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

int main() {
    int value = 5;
    ShowValue(value); // Shows 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 Greet(const std::string &name = "World") {
    std::cout << "Hello, " << name << "!" << std::endl;
}

int main() {
    Greet();          // Shows "Hello, World!"
    Greet("John");   // Shows "Hello, John!"
    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 PrintNumbers(int count, ...) {
    va_list args;
    va_start(args, count);
    for (int i = 0; i < count; ++i) {
        int number = va_arg(args, int);
        std::cout << number << " ";
    }
    va_end(args);
    std::cout << std::endl;
}

int main() {
    PrintNumbers(5, 1, 2, 3, 4, 5); // Shows 1 2 3 4 5
    return 0;
}