Passing Parameters by Value and Reference

In C++ we have two basic ways to pass parameters to a function:

  1. Pass by value
  2. Pass by reference

When passing by value, a copy of the variable is created. Changes inside the function therefore don't affect the original variable. This is what we've been using so far:

void changeNumberByValue(int number) {
    number = 42;  // Changes only the local copy
}

int x = 10;
changeNumberByValue(x);
std::cout << x;  // Prints: 10 (x hasn't changed)

When passing by reference, the function works directly with the original variable. Changes inside the function therefore affect the original variable:

void changeNumberByReference(int& number) {
    number = 42;  // Changes the original variable
}

int x = 10;
changeNumberByReference(x);
std::cout << x;  // Prints: 42 (x has changed)

Passing by reference is useful when:

  • We want the function to be able to change the original variable
  • We want to pass large objects without creating a copy (more efficient)

If we don't want the function to be able to change the passed variable, but want to avoid copying, we can use a constant reference (const&):

void printVector(const std::vector& vector) {
    // vector cannot be changed, but no copy is made
    for(int number : vector) {
        std::cout << number << " ";
    }
}

Instructions

Look at the program output. Why didn't the value of variable a change, but the value of b did?

Modify the doubleIt function so that it can also change the original value. Hint: Use a pointer or reference.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

2/5

Passing Parameters by Value and Reference | Start Coder