C++ · Module 5 · Lesson 21 min read

Pass by Value, Reference & const Reference

Pass by value (default)

scss
void f(int x) { x = 100; }   // changes the COPY only
  • The function gets its own copy
  • Safe: the caller's variable can't change
  • ✅ Best for small, cheap types: int, double, char, bool, small structs

Pass by reference &

arduino
void deposit(double& balance, double amount) { balance += amount; }
  • The parameter is an alias for the caller's variable
  • Changes affect the original
  • Use when the function's job is to modify the argument (output parameters)

Pass by const reference const & ✅

c
void print(const std::string& name) { ... }
  • No copy (fast for big objects: strings, vectors, structs)
  • Can't modify it (safe)
  • The default choice for large read-only parameters

Decision table

ParameterSmall type (int, double)Large type (string, vector, struct)
Only read itby valueconst&
Modify the caller's variable&&
Need my own copy anywayby valueby value (then std::move it, Unit 10)

Copying cost

Passing a std::vector<int> with a million elements by value copies 4 MB on every call!

References must refer to something

  • Can't be null, can't be re-seated
  • Non-const references can't bind to temporaries: deposit(500.0, 10) ❌
  • const& can bind to temporaries: print("Asha") ✅

Returning multiple results

Output reference parameters work, but returning a struct, std::pair or std::tuple is usually clearer (lesson 5.6).

Pointers (Unit 7)

C-style "pass by pointer" (int* p) also allows modification and can express "optional" (nullptr). In modern C++, prefer references unless null is meaningful.

Example

C++
#include <iostream>
#include <string>
#include <vector>

void try_to_change(int x) { x = 100; std::cout << "inside: x = " << x << '\n'; }   // changes the copy
void deposit(double& balance, double amount) { balance += amount; }   // modifies the original

double total(const std::vector<double>& items) {           // no copy, read-only
    double sum = 0;
    for (double x : items) sum += x;
    // items.push_back(1);                                  // error: items is const
    return sum;
}

void greet(const std::string& name) { std::cout << "Namaste, " << name << "!\n"; }

void min_max(const std::vector<int>& v, int& lo, int& hi) {   // output parameters
    lo = hi = v.front();
    for (int x : v) {
        if (x < lo) lo = x;
        if (x > hi) hi = x;
    }
}

void swap_values(int& a, int& b) {
    int temp = a;
    a = b;
    b = temp;
}

int main() {
    int n = 5;
    try_to_change(n);
    std::cout << "after try_to_change: n = " << n << '\n';

    double balance = 1000;
    deposit(balance, 2500);
    std::cout << "after deposit: balance = " << balance << '\n';

    std::vector<double> bills = { 1500, 800, 2200.5 };
    std::cout << "total bills = " << total(bills) << '\n';

    greet("Sita");                      // const& binds to a temporary string
    int lo, hi;
    min_max({ 42, 7, 93, 15 }, lo, hi);
    std::cout << "min = " << lo << ", max = " << hi << '\n';

    int x = 1, y = 2;
    swap_values(x, y);
    std::cout << "after swap: x = " << x << ", y = " << y << '\n';
    return 0;
}

/* Output:
inside: x = 100
after try_to_change: n = 5
after deposit: balance = 3500
total bills = 4500.5
Namaste, Sita!
min = 7, max = 93
after swap: x = 2, y = 1
*/