Const Reference in C++
In the “pass by const reference” technique, a const reference (also known as an alias) to the original argument is passed. This means that we cannot modify the actual parameters within the function. By using a reference, we avoid making a copy of the argument, so we can also pass large objects or parameters to functions.
Syntax for Const Reference Parameter Passing
returnType functionName(const dataType& paramName);
Example
The below example demonstrates how we can pass by const reference in C++.
// C++ program to demonstrate pass by const reference
#include <iostream>
using namespace std;
// function to modify the value
void increase(const int& num)
{
num += 5; // Error: read-only variable is not assignable
}
int main()
{
// define avariable
int x = 10;
// calling increase function by passing parameter x
increase(x);
// printing the variable x
cout << x;
return 0;
}
Output
error: assignment of read-only reference ‘num’
Explanation: In the above example, compiler throws a compile-time error because here we are trying to modify a read-only reference which is not possible.
Const Reference vs Normal Parameter Passing in C++
In C++, when we call a function we can also pass the parameters to the function in many ways like pass by value, pass by reference, pass by pointer, and by const reference. Each parameter-passing technique has its own advantages and disadvantages. In this article, we will learn the difference between normal parameter passing and passing by const reference in C++.
Contact Us