In the functions that we created in previous posts, their parameters have always been passed by value. This means that, when we call a function, what is passed to the function are the values of these parameters on that moment of the call. Variables are copied into the variables represented by the function parameters. Let’s remember an example,
Here x and y values are copied to a and b parameters and returned with addition.
We can access to its parameters directly by using its parameters as references. In C++, references are indicated with an ampersand (&
) following the parameter type, it points the address of the variable. So we can modify our function parameters as a reference parameters by using & character before their variable names.
Here we passed x and y by itself, and we didn’t do copy operation on a & b variables of our function. If a variable is passed by reference that means it is passed without a copy operation, just addressing the variable itself. The variable identified by the function parameter, becomes somehow associated with the argument passed to the function. This allows users to do modification on their corresponding local variables within the function are reflected in the variables passed as arguments in the call. Referencing is important to eliminate copy operations and speeds up functions.