C++ · Beginner level

Beginner level · Module 2: Control Flow and Functions in C++ · Lesson 3 of 3

Passing by Value, Reference and const Reference

Understand how arguments are passed and choose the right form for speed and safety.

In this lesson you will

  • Explain pass by value and by reference
  • Use const references for large read-only arguments

Key concepts

pass by valuereference parameter (&)const referencecopy cost

The lesson

By default C++ copies arguments: void addFee(int balance) changes only its own copy. To let a function change the caller's variable, pass by reference: void addFee(int& balance). The & means the parameter is another name for the original variable.

Copying large objects such as a std::vector with thousands of items is slow. Pass them by const reference — double average(const std::vector<int>& marks) — which avoids the copy and lets the compiler stop the function from changing them.

A simple rule: pass small built-in types (int, double, char) by value; pass objects you only read by const reference; pass by non-const reference only when the function's job is to change the argument.

Step by step

  1. Write a function that tries to change an int passed by value.
  2. Change it to take an int& and compare the result.
  3. Write average(const std::vector<int>&).
  4. Try to modify the vector inside it and read the compiler error.

Practice activity

Write functions that update a student's balance (by reference) and calculate statistics on a list of payments (by const reference).

Expected result: Balances change only through the update function, and the statistics function cannot modify the list.

Check your understanding

  1. What does int& in a parameter mean?

    Show answer

    The parameter refers to the caller's variable, so changes affect it.

  2. How should a large vector that is only read be passed?

    Show answer

    By const reference.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.