Pular para o conteúdo principal
Módulo 3 · Lição 2 de 28/18 no curso~12 min
Lições do módulo (2/2)

Passar por valor e referência

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.

Passar por Valor (Cópia)

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:

C++
#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 (&)

Se quiser que a função seja capaz de modificar a variável original, ou se quiser evitar copiar objetos grandes (como cadeias longas ou vetores), você deve usar passar por referência.

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

C++
#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

Exercício#cpp.m3.l2.e1
Tentativas: 0Carregando…

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.

Carregando editor…
Mostrar dica

The function signature uses the `&`character after the type to indicate a reference:`void doubleNumber(int& n)`.

Solução disponível após 3 tentativas

Exercício#cpp.m3.l2.e2
Tentativas: 0Carregando…

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.

Carregando editor…
Mostrar dica

Use `int temp = a; a = b; b = temp;` to swap the values.

Solução disponível após 3 tentativas