Skip to main content
eLearner.app
Module 3 · Lesson 2 of 28/18 in the course~12 min
Module lessons (2/2)

Pass by value and reference

In C++, when you pass an argument to a function, there are two main ways to do it: by value or by reference.

Understanding this distinction is key to both program correctness and performance optimization.

Pass by Value (Copy)

By default, C++ passes arguments by value. This means a copy of the data is created in memory. Any modification made inside the function will not affect the original variable outside:

Code
#include <iostream>

void increment(int n) {
    n++; // Modifies only the local copy
}

int main() {
    int x = 5;
    increment(x);
    std::cout << x << std::endl; // Prints 5, x remains unchanged!
    return 0;
}

Pass by Reference (&)

If you want the function to be able to modify the original variable, or if you want to avoid copying large objects (like long strings or vectors), you must use pass by reference.

A reference is declared by adding the & symbol after the parameter's type:

Code
#include <iostream>

void incrementRef(int& n) {
    n++; // Modifies the original variable directly
}

int main() {
    int x = 5;
    incrementRef(x);
    std::cout << x << std::endl; // Prints 6!
    return 0;
}

The parameter int& n is not a copy, but an alias (a direct reference) to the variable x passed when calling the function.

Try it yourself

Exercise#cpp.m3.l2.e1
Attempts: 0Loading…

Define a function named doubleNumber with a void return type that takes a reference to an integer n (using int& n) and doubles its value (n = n * 2). Call it in main passing the variable val initialized to 10, then print val.

Loading editor…
Show hint

La firma della funzione usa il carattere `&`dopo il tipo per indicare un riferimento:`void doubleNumber(int& n)`.

Solution available after 3 attempts

Exercise#cpp.m3.l2.e2
Attempts: 0Loading…

Define a function named swap that takes two integer references a and b (int& a, int& b) and swaps their values using a temporary variable temp. Call it in main to swap x and y, and then print them.

Loading editor…
Show hint

Usa `int temp = a; a = b; b = temp;` per scambiare i valori.

Solution available after 3 attempts