Skip to content
LumenaryAcademy
Foundations 55 min

Values, references and const

What a C++ variable really holds, how copies and aliases differ, and how const lets the compiler hold you to your word.

Code tested · 3AI-draftedAwaiting review by a computer scientist
MotivationH

What does a variable hold?

In Python, b = a makes b a second name for the same list. Change the list through b and a sees the change. Java and JavaScript behave the same way for objects. Many people arrive at C++ expecting this, and are surprised.

In C++, a variable is the object. std::vector<int> b = a; builds a whole new vector and copies every element into it. Afterwards the two have nothing to do with each other. This is called value semantics, and it is the single most important difference between C++ and the garbage-collected languages. It makes programs easier to reason about (nobody can change your vector behind your back), it lets objects live directly on the stack or inside other objects with no extra allocation, and it is why C++ has a whole vocabulary — references, const, pointers, views and, later, moves — for the times when you do not want a copy.

This lesson is about that vocabulary. Get it right and most of the rest of the language makes sense.

IntuitionH

Boxes, not labels

Analogy, not a formal construction

Think of a C++ variable as a box with a fixed shape, sitting at a fixed place in memory, with a value inside. int b = a; builds a second box and copies what is in a into it. A reference is not a box at all: it is a second label stuck on an existing box. A pointer is a box whose contents are the location of another box, written down like a street address.

Two consequences follow. First, the size of every box is known when the program is compiled, so the compiler can lay out memory exactly: an int usually takes 4 bytes, a double 8, and a struct holding both takes their sizes plus any padding. Second, every box has a lifetime: it is created when its declaration runs and destroyed when its scope (the enclosing { }) ends. A label or an address that outlives the box it refers to is said to dangle, and using it is one of the classic C++ bugs.

Where do the boxes live? Local variables live on the stack, a region of memory that grows when a function is called and shrinks when it returns, which makes creating and destroying them almost free. Objects whose size is only known while the program runs, such as the elements of a std::vector or the characters of a long std::string, live on the free store (often called the heap). The vector object itself is a small box on the stack holding a pointer to its elements, its size and its capacity. When you copy a vector, C++ copies the elements too, into a new block on the free store, so that the copy is fully independent. That is what makes value semantics safe, and also what makes careless copies expensive.

DefinitionsH

Types, initialisation and the words for not copying

C++'s fundamental types are integers (int, long, long long, short, each with an unsigned version), characters (char), bool, and floating point (float, double). The standard only fixes minimum sizes for most of them: int is at least 16 bits and is 32 bits on every desktop and server platform today, while long is 64 bits on Linux and macOS but 32 bits on Windows. When the exact width matters (file formats, network protocols, hashing), use the fixed-width types from <cstdint>: std::int32_t, std::uint64_t and friends. std::size_t is the unsigned type the library uses for sizes.

Definition— initialisation

Giving a variable its first value as it is created. int n = 3;, int n(3); and int n{3}; all initialise. The brace form forbids narrowing: int n{2.9}; is a compile error, while int n = 2.9; silently stores 2. A local variable of a fundamental type declared with no initialiser (int n;) holds an indeterminate value, and reading it is a bug: undefined behaviour before C++26, which turns it into "erroneous behaviour" that implementations are encouraged to diagnose.

Definition— auto

auto x = expression; gives x the type of the expression, worked out at compile time. It does not make x dynamically typed. auto drops top-level const and references, so auto copy = some_reference; makes a copy; write auto& or const auto& when you want a reference.

Definition— reference

T& r = x; makes r another name for the existing object x. A reference must be initialised, cannot be made to refer to something else later, and cannot be null. const T& r is a reference through which the object can be read but not changed.

Definition— pointer

T* p = &x; stores the address of x; *p is the object it points at. Unlike a reference, a pointer can be reassigned and can be nullptr, meaning "points at nothing". In modern C++ a plain pointer never owns what it points at; it is an observer. Ownership is the job of the smart pointers in a later lesson.

Definition— const and constexpr

const on a variable means it cannot be changed after initialisation. constexpr means more: the value can be computed by the compiler, so it can be used where a compile-time constant is required, such as an array size or a static_assert. A constexpr function can run at compile time when its arguments are known then, and at run time otherwise.

Definition— std::string_view

A small, cheap-to-copy object holding a pointer to some characters and a length. It lets a function read text from a std::string, a string literal or part of either without copying it. It does not own the characters, so it must not outlive them.

ComputationC

Seeing it run

First, the numbers. This program asks the compiler how big some types are, and shows what braces, auto and unsigned types do.

cpp
#include <cstdint>
#include <limits>
#include <print>

int main() {
    std::println("int: {} bytes, max {}", sizeof(int), std::numeric_limits<int>::max());
    std::println("long long: {} bytes", sizeof(long long));
    std::println("double: {} bytes, about {} significant digits",
                 sizeof(double), std::numeric_limits<double>::digits10);

    std::int64_t population = 8'200'000'000;   // ' separates digits (C++14)
    std::uint8_t level = 255;
    level += 1;                                // 256 does not fit: unsigned types wrap to 0
    std::println("population {}, level {}", population, level);

    auto ratio = 2 / 3.0;      // auto: the type comes from the initialiser (double)
    auto count = 10u;          // unsigned int
    std::println("{:.4f} {}", ratio, count);

    int a = 7;
    // int b{2.9};             // error: narrowing conversion from double to int
    int c = 2.9;               // compiles, silently drops the .9 (and -Wall is quiet here)
    std::println("{} {}", a, c);

    bool ready = (a > 5) && (c == 2);
    std::println("{}", ready);
}
text
int: 4 bytes, max 2147483647
long long: 8 bytes
double: 8 bytes, about 15 significant digits
population 8200000000, level 0
0.6667 10
7 2
true

Unsigned integers wrap around: arithmetic on them is defined modulo 2 to the power of their width, which is why 255 + 1 stored in 8 bits is 0. Signed integers do not get that promise. If an int calculation overflows, the behaviour is undefined, and optimisers are allowed to assume it never happens. When a value might grow large, choose a wider type; when you need wrapping (hashes, checksums), use an unsigned type deliberately. The silent int c = 2.9; is caught by -Wconversion, a warning many teams add to -Wall -Wextra, and is impossible with braces.

Next, copies and aliases.

cpp
#include <print>
#include <string>
#include <vector>

void shout(std::string text) {       // takes a copy
    text += "!";
    std::println("inside: {}", text);
}

void shout_in_place(std::string& text) {   // takes a reference
    text += "!";
}

int main() {
    std::string greeting = "jambo";
    std::string copy = greeting;     // a new, independent string
    copy[0] = 'J';
    std::println("{} {}", greeting, copy);

    std::vector<int> scores{70, 85, 90};
    std::vector<int> backup = scores;   // copies all three elements
    scores.push_back(100);
    std::println("{} {}", scores.size(), backup.size());

    shout(greeting);
    std::println("after shout: {}", greeting);
    shout_in_place(greeting);
    std::println("after shout_in_place: {}", greeting);

    int x = 1;
    int& alias = x;     // another name for x
    alias = 42;
    std::println("x = {}", x);
}
text
jambo Jambo
4 3
inside: jambo!
after shout: jambo
after shout_in_place: jambo!
x = 42

Every line of output follows from one rule: a plain variable or parameter is its own object, and a reference is a name for someone else's. shout changed its private copy; shout_in_place changed the caller's string.

Finally, const, constexpr, pointers and views.

cpp
#include <print>
#include <string>
#include <string_view>

constexpr double kilometres_per_mile = 1.609344;

constexpr int square(int n) { return n * n; }

std::string_view first_word(std::string_view text) {
    auto space = text.find(' ');
    return text.substr(0, space);   // a view into the caller's characters, no copy
}

void count_vowels(const std::string& s, int& out) {   // read s, write out
    out = 0;
    for (char ch : s) {
        if (std::string_view("aeiou").contains(ch)) ++out;   // contains: C++23
    }
}

int main() {
    static_assert(square(12) == 144);   // checked by the compiler, not at run time
    std::println("{:.1f} km", 26.2 * kilometres_per_mile);

    std::string line = "ubuntu means humanity to others";
    std::println("first word: {}", first_word(line));

    int vowels = 0;
    count_vowels(line, vowels);
    std::println("vowels: {}", vowels);

    int height = 180;
    int* p = &height;          // p holds the address of height
    *p += 5;                   // change height through p
    int* nothing = nullptr;    // a pointer may point at nothing; a reference may not
    std::println("{} {}", height, nothing == nullptr);

    const int limit = 3;
    // limit = 4;              // error: assignment of read-only variable
    std::println("limit {}", limit);
}
text
42.2 km
first word: ubuntu
vowels: 11
185 true
limit 3

count_vowels shows a style you will see in older code: an "out parameter" (int& out) used to hand back a result. Modern C++ prefers to return results, even large ones, because returning a local object is cheap (you will see why in the lesson on move semantics). Use out parameters only when a function genuinely updates something the caller already has.

Worked examplesH

How to pass a parameter

The question "copy, reference or const reference?" comes up in every function you write. Experienced C++ programmers follow a short rule of thumb, which the C++ Core Guidelines also recommend:

The function will...Parameter typeExample
only read a cheap value (numbers, char, bool, small structs, views)by value: Tdouble area(double r)
only read something expensive to copyconst T&int count(const std::vector<int>& v)
read any textstd::string_viewbool is_title(std::string_view s)
change the caller's objectT&void normalise(std::vector<double>& v)
keep its own copy (store it in a member, say)by value: T, then move it (later lesson)void set_name(std::string name)

"Cheap" means roughly the size of two or three pointers. A std::string or a std::vector is not cheap to copy, because copying it copies everything it holds.

Example— Reading const with pointers

With pointers there are two things that could be constant: the pointer itself, and the object it points at. The trick for reading such declarations is to go from right to left, starting at the name:

cpp
int value = 10, other = 20;

const int* a = &value;    // a is a pointer to a const int
a = &other;               // fine: a itself may point elsewhere
// *a = 5;                // error: cannot change the int through a

int* const b = &value;    // b is a const pointer to an int
*b = 5;                   // fine: the int may change
// b = &other;            // error: b always points at value

const int* const c = &value;   // neither may change

const int* and int const* mean the same thing; some codebases put const after the type ("east const") so that the right-to-left rule works without exception, and most put it first. Pick whichever your project uses. In practice you will mostly meet const T* ("a pointer through which I only read") and const T&, and rarely need a const pointer itself.

Example— The signed–unsigned trap

v.size() returns an unsigned std::size_t. Compare it with a negative int and the int is converted to unsigned first, becoming a huge number:

cpp
std::vector<int> v{1, 2, 3};
int i = -1;
std::println("{}", i < v.size());                 // false!
std::println("{}", std::cmp_less(i, v.size()));   // true (C++20, <utility>)

GCC warns about the first comparison when -Wall is on:

text
main.cpp:8:26: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]

and the program prints false then true. std::cmp_less compares the mathematical values correctly. Another common fix is std::ssize(v) (C++20), which returns the size as a signed number.

Example— A view that outlives its string

A std::string_view is only safe while the characters it points into are alive:

cpp
std::string_view label() {
    std::string s = "temporary";
    return s;                // compiles: converts to a view of s's characters...
}                            // ...and s is destroyed here. The view now dangles.

Using the returned view is undefined behaviour. It may even appear to work, because the destroyed characters are often still sitting in memory. The same goes for returning a reference to a local variable. The rule: a function may return a view or reference into something its caller owns (as first_word above does), never into its own locals. Return a std::string when you are creating new text.

Common misconceptionsH

Common misconceptions

Misconception

"auto makes C++ dynamically typed." auto asks the compiler to write the type for you; the type is still fixed at compile time and checked everywhere. Many teams use auto wherever the type is obvious from the right-hand side, and spell the type out where it helps the reader.

Misconception

"A const& parameter guarantees the object will not change." It guarantees that this function will not change it through that reference. Another reference to the same object, or another thread, may still change it. const is a promise about access, not a property of the object everywhere.

Misconception

"Passing by reference is always faster." For small values a reference can be slower: it forces the object to live in memory and makes every access an indirection, and it makes it harder for the optimiser to know that nothing else changes the value. Pass numbers and views by value.

Misconception

"References are just pointers with nicer syntax." Compilers often implement them that way, but the rules differ in ways that matter: a reference is always bound to an object, is never null, and can never be reseated. Choose a reference when "always refers to exactly this object" is what you mean, and a pointer when "might be nothing" or "may change what it points at" is.

ExplanationH

What professionals do

Three habits cover most of this lesson. Initialise everything, preferably at the point of declaration, and prefer braces when narrowing would be a bug. Make things const by default and remove the const only when something genuinely needs to change; it documents intent and lets the compiler catch accidental writes. And think about lifetimes whenever you take a reference, pointer or view: who owns the object, and will it still be alive when I use this?

Tools help with the last one. GCC and Clang warn about some dangling references, static analysers such as clang-tidy flag more, and the AddressSanitizer you will use in the Professional level catches many uses of destroyed objects at run time. None of them catches everything, which is why the habit matters.

Exercises

Exercises

1. Values, references and const

Warm-upComputational

What does this program print?

#include <print>

int main() {
    int a = 5;
    int b = a;
    int& r = a;
    b += 1;
    r *= 10;
    std::println("{} {} {}", a, b, r);
}

2. Values, references and const

Warm-upComputational

What number does this program print?

#include <print>

void f(int x) { x = x * 2; }
void g(int& x) { x = x + 3; }

int main() {
    int n = 4;
    f(n);
    g(n);
    f(n);
    std::println("{}", n);
}

3. Values, references and const

CoreComputational

On a platform where unsigned int is 32 bits (every mainstream desktop and server), what does this print?

#include <print>

int main() {
    unsigned int u = 0;
    u -= 1;
    std::println("{}", u);
}

4. Values, references and const

CoreComputational

What does this program print?

#include <print>
#include <vector>

int main() {
    std::vector<int> v{1, 2, 3};
    auto w = v;
    auto& u = v;
    w.push_back(4);
    w.push_back(6);
    u.push_back(5);
    std::println("{} {} {}", v.size(), w.size(), u.size());
}

5. Values, references and const

CoreHuman

Which of these lines are compile errors? Select all that apply. Assume double d = 2.5; and int x = 1, y = 2; were declared earlier.

Choose all that apply

6. Values, references and const

StretchHuman

Which function has a dangling result that makes using its return value undefined behaviour?

Choose one

7. Values, references and const

CoreHuman

What does constexpr add, compared with const, in constexpr int size = 64;?

Choose one

Further reading and resources