Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 171 ยท Functions

Parameters: by Value, by Reference and by const Reference

Learn how to pass arguments in C++ - by value, by reference and by const reference, what each costs, output parameters and better alternatives, and passing strings and vectors.

Every time you call a function, each argument has to get into a parameter somehow. C++ gives you a choice that many languages hide: the parameter can be a copy of the argument, or it can refer to the caller's original object. The choice decides whether the function can change the caller's data, and how much work the call costs. Passing a 10-megabyte vector by copy, a thousand times in a loop, is a performance bug that compiles without a single warning.

This lesson covers the three everyday ways to pass parameters (by value, by reference and by const reference), a simple rule for choosing between them, how to pass strings, arrays and vectors efficiently, and why output parameters are usually better replaced by return values. You'll also meet a subtle bug called aliasing that catches even experienced programmers.

Parameters and arguments

First, the vocabulary. A parameter is the variable declared in the function's parameter list. An argument is the value or expression you pass at the call site:

C++
int area(int width, int height);   // width and height are parameters
area(4, 5);                        // 4 and 5 are arguments

When the call happens, each parameter is initialized from its argument, exactly as if you wrote int width = 4;. The type of the parameter decides what that initialization means.

Pass by value: the function gets a copy

A parameter declared with a plain type (int x, std::string s, std::vector<int> v) is passed by value. It's a brand-new object, initialized as a copy of the argument. The function can change it freely, and the caller never sees the change:

C++
void reset(int counter) {
    counter = 0;          // changes the local copy only
}

int clicks = 42;
reset(clicks);            // clicks is still 42

By value is simple and safe: the function and the caller can't interfere with each other. For small types like int, double, char or a pointer, copying is just a few bytes and costs nothing worth measuring. The problem is large objects: copying a std::string or std::vector means allocating memory and copying every character or element.

Pass by reference: the function works on the original

Adding & to the parameter type makes it a reference: another name for the caller's object (see References for the full story). No copy is made, and every change inside the function happens to the original:

C++ Value vs reference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

shout_copy changes only its own copy, so message is still hello afterwards; shout_in_place changes the original. swap_values can only work with references, because it must change the caller's two variables. (The standard library already provides it as std::swap in <utility>.)

The & appears only in the parameter list. The call site looks the same as a by-value call, which is the main criticism of non-const references: reading add_bonus(scores, 5), you can't tell that scores will change. Good function names make up for that.

A non-const reference must bind to a real, modifiable object. Passing a literal or the result of an expression is a compile error:

C++
void double_it(int& x) { x *= 2; }

double_it(5);       // error: cannot bind non-const lvalue reference of type 'int&' to an rvalue of type 'int'
double_it(a + b);   // same error: a + b is a temporary value, not a variable

That's a feature: "double this temporary" would be meaningless, because the result would be thrown away immediately.

Pass by const reference: no copy, no changes

Most of the time a function only needs to read a large argument. const T& gives you the best of both worlds: like a reference, it doesn't copy; like a value, the function can't modify the caller's object. Trying to change it is a compile error.

const T& is also more flexible than T&: it accepts temporaries and literals. print_line("hi") works with a const std::string& parameter; the compiler creates a temporary std::string that lives until the call returns.

To see what copies cost, the next example uses a small type that announces every time it is copied. (The Tracked(const Tracked&) line is a copy constructor, which runs whenever an object is copied; you'll learn to write them in Copy Constructors and Copy Assignment. Here it simply counts.)

C++ Counting copies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Fifty calls by value made fifty copies of a 4 MB vector, about 200 MB of memory traffic, to compute a sum that never needed one. The const& version made none. The totals are identical; only the cost differs.

Choosing how to pass a parameter

The decision comes down to two questions: will the function modify the caller's object? and is the type cheap to copy?

The function... Parameter type Examples
Reads a cheap-to-copy value T (by value) int, double, char, bool, enums, pointers, std::string_view, std::span
Reads an expensive object const T& const std::string&, const std::vector<T>&, large structs
Modifies the caller's object T& std::vector<int>& results, int& counter
Keeps its own copy (stores it, returns a changed version) T (by value), then std::move a constructor storing a name

"Cheap to copy" means roughly "fits in two or three machine words and has no heap memory". For those types, by value is not only simpler but often faster than a reference, because the value can travel in a CPU register, while a reference is an address the function must follow on every use.

The last row deserves a word. If a function is going to store a string anyway (say, in a struct), taking it by value and moving it into place lets callers pass temporaries without any copy at all:

C++
struct Contact {
    std::string name;
};

void rename(Contact& contact, std::string new_name) {   // a copy only if the caller passes a variable
    contact.name = std::move(new_name);                 // steal the buffer instead of copying again
}

std::move comes from <utility>; Move Semantics explains what "moving" means. Until then, the first three rows cover nearly every function you'll write.

A const on a by-value parameter, like void f(const int x), only stops the function body from changing its own copy. It makes no difference to the caller and isn't part of the function's type, so void f(int) and void f(const int) declare the same function. Some teams use it inside definitions as a "won't change" marker; it's optional.

Passing strings, arrays and vectors efficiently

Containers are where the choice matters most, and modern C++ has dedicated view types that are often better than a reference.

Strings you only read: use std::string_view (by value), introduced in std::string_view. It accepts a std::string, a string literal or a char array with no allocation, while const std::string& must build a temporary std::string when given a literal. Use const std::string& when you need to pass the string on to an API that requires a std::string or a null-terminated c_str().

Sequences you only read: use std::span<const T> (std::span), which accepts a vector, a std::array, a C array or a slice of any of them. const std::vector<T>& works too, if the callers always have a vector.

Containers you modify in place: std::span<T> to change elements, std::vector<T>& to add or remove elements.

C arrays decay to pointers when passed (see C-Style Arrays), so a raw array parameter is never a copy; prefer a span to keep the size.

C++ Views as parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

count_vowels handles an owning string, a literal and a substring view with the same signature and zero copies. (std::string_view::contains is C++23.) largest takes a vector and a C array alike. append_squares genuinely needs std::vector<int>&, because a view can't grow the container.

Output parameters and better alternatives

A non-const reference parameter used only to send a result back is called an output parameter. It's common in C and older C++:

C++
void min_max(const std::vector<int>& values, int& min_out, int& max_out);

int lo, hi;              // must exist (and be uninitialized) before the call
min_max(data, lo, hi);   // nothing at the call site says lo and hi are outputs

Output parameters have real drawbacks: the caller must declare variables in advance, the data flow is hidden, and the results can't be const. Modern C++ prefers to return results, even several of them, because returning is cheap (the compiler builds the result directly in the caller's variable or moves it):

C++ Return results instead of output parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Both versions find 3 and 21, but the returned struct can be unpacked into const variables in one line, and the call site makes the data flow obvious. std::optional replaces the old "return true and fill an output parameter" pattern. Returning Values covers structs, pairs, tuples and std::optional in depth. (Both functions assume a non-empty vector; front() on an empty one is undefined behavior.)

Output parameters still have a place: when a function fills a buffer the caller owns and reuses across calls (for example, reading lines into the same std::string to avoid reallocating, as std::getline(std::cin, line) does), or when a function modifies an object as its main purpose, as add_bonus did earlier.

The aliasing trap

References introduce a subtle problem: two parameters might refer to the same object. This is called aliasing, and a function that doesn't expect it can produce wrong answers:

C++ When two parameters are the same object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The intended result is [20, 30, 40]. The const int& version prints [20, 40, 50]: after the first iteration, values[0] is 20, and amount is values[0], so the remaining elements get 20 added. const only means "this function won't modify the object through this name"; it doesn't promise that nothing else will. Passing the small int by value, as the guidelines table recommends anyway, removes the problem. Standard library functions like std::vector::push_back are written to handle aliasing correctly (v.push_back(v[0]) is safe), but your own functions need the same care.

Pointers as parameters

You'll also see parameters of pointer type, like void draw(const Shape* shape). A pointer can be nullptr, so it's the traditional way to express an optional argument that the function may modify or inspect. In modern code, prefer references when the argument is required (a reference can't be null), and consider std::optional or an overload when it isn't. Pointers get their own lessons in Pointers and const with Pointers and References.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? void f(std::vector<int> v) { v.push_back(4); } then std::vector<int> nums{1, 2, 3}; f(nums); std::println("{}", nums.size());

    v is passed by value, so f appends to its own copy. The caller's nums still has 3 elements.
  2. 2. Which parameter type is the best default for a function that only reads a large std::vector<double>?

    A const reference or a span avoids the copy and prevents accidental modification. A non-const reference would allow changes and reject temporaries.
  3. 3. Given void bump(int& x);, which call compiles?

    A non-const lvalue reference can only bind to a modifiable object such as a variable. Literals and results of expressions are temporaries and are rejected.
  4. 4. For a function that reads an int, why is by value usually better than const int&?

    Small types fit in a register, so a copy costs nothing, and it can't change behind the function's back the way a reference to an aliased object can.
  5. 5. Why do modern guidelines prefer returning a struct over two output parameters for a min/max function?

    const auto [lo, hi] = min_max(v); shows exactly what comes out, and copy elision or moves make returning a small struct essentially free.

Summary

  • Parameters are initialized from arguments; the parameter's type decides whether that's a copy or a reference.
  • By value (T): the function gets its own copy. Best for cheap types such as int, double, pointers, std::string_view and std::span.
  • By reference (T&): the function works on the caller's object and can modify it; it can't bind to literals or temporaries.
  • By const reference (const T&): no copy and no modification, and it accepts temporaries. The default for reading large objects.
  • For read-only strings use std::string_view; for read-only sequences use std::span<const T>; to add or remove elements pass std::vector<T>&.
  • Prefer returning results (structs, structured bindings, std::optional) over output parameters.
  • Beware aliasing: a reference parameter may refer to an object the function is also modifying through another name.

Next: Default Arguments, where you'll give parameters default values so callers can leave them out.