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++
// 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++.

Similar Reads

Normal Parameter Passing in C++

In C++, normal parameter passing is also known as “pass-by-value“, in this parameter passing technique the compiler creates a copy of the argument being passed. Any changes made to formal parameters within a function are not reflected in the original arguments. If the parameters passed are very large, then the copying process becomes very tedious and results in wasting our storage and CPU cycles....

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....

Difference Between Const Reference and Normal Parameter Passing

The below table demonstrates the key differences between const reference and normal parameter passing:...

Conclusion

In conclusion, the choice between const reference and normal parameter passing in C++ depends on the specific requirements of our program. If we’re working with large objects and want to avoid the overhead of copying, const reference can be a good choice. However, if we want the function to modify the arguments within oour function, normal parameter passing will be preferred....