CodeBlanks Logo Icon CodeBlanks

const references

Learn safe and efficient passing with const references.

const references

If you do not want a parameter to be modified, use a const reference: void printValue(const int& n). This means n is read-only and is not copied.

A const reference is both safe and efficient. Safe, because the function cannot accidentally change the caller's variable. Efficient, because large objects are not copied. So when passing types like std::string or std::vector to a function, const T& is preferred.

Why const reference?

Passing a large object to a function by value is expensive, because the whole object is copied. Pass by reference avoids the copy but allows the function to modify the object.

To get both benefits, use a const reference: no copy, no modification. This is the standard way to pass large objects to a function in C++. For example void print(const std::string& s).

Practice The printValue function

Define a void printValue(const int& n) function; in the body print n with std::cout. In main declare int x = 7; and call printValue(x).

Starter code

main.cpp
#include <iostream>

// Define the printValue function

int main() {
    // Declare x
    // Add a printValue call
    return 0;
}

Sample solution

main.cpp
#include <iostream>

void printValue(const int& n) {
    std::cout << n << "\n";
}

int main() {
    int x = 7;
    printValue(x);
    return 0;
}

Expected output

7

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 const reference parameter

Question
void printValue(____ int& n) { std::cout << n; }
Answer
void printValue(const int& n) { std::cout << n; }

Explanation: const int& n is a read-only reference parameter.

2 Which is a const reference declaration?

  • const int p;
  • int const p = x;
  • const int& r = x; Correct answer
  • int& const r = x;

Explanation: const int& r = x; declares a read-only reference.

3 Match each expression to its meaning

Term Meaning
const int& n Const reference
printValue(x) Call
void Returns no value
n Read-only

All lessons in Beginner