How to use function references in C++?

In C++, referencing a function is done by declaring the return type of a function as a reference type and using a reference variable to store the returned value.

For example, declaring a function that returns a reference type would look like this:

int& increment(int& num) {
    num++;
    return num;
}

The function above takes an integer reference as a parameter, increments its value by 1, and returns the reference to the parameter.

You can call a referenced function using the following methods:

int main() {
    int num = 5;
    int& result = increment(num);
    std::cout << "Result: " << result << std::endl;
    return 0;
}

In the example above, the variable num is passed by reference to the increment function and the returned reference is assigned to the result variable. Then, the value of result is printed.

The output will be:

Result: 6

It can be seen that by referencing the return value of a function, the value of the passed variable can be directly modified.

bannerAds