C++ functions: Constant Reference Parameters

You can specify a constant reference parameter to prevent its value from being changed by accident.

If your program uses a pass-by-reference parameter and the parameter is not changed in the function, you should mark it constant to tell the compiler that the parameter should not be changed. To do so, place the const keyword before the parameter in the function declaration. Such a parameter is known as constant reference parameter. For example, numl and num2 are declared as constant reference parameters in the following function.

// Return the max between two numbers

int max(const int& num1, const int& num2)

{

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}

In pass-by-value, the actual parameter and its formal parameter are independent variables. In pass-by-reference, the actual parameter and its formal parameter refer to the same vari­able. Pass-by-reference is more efficient than pass-by-value for object types such as strings, because objects can take a lot of memory. However, the difference is negligible for parameters of primitive types such int and double. So, if a primitive data type parameter is not changed in the function, you should simply declare it as pass-by-value parameter.

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *