๐ŸŽ“ A1Learner
๐Ÿ”

C++ References

A reference is a second name for a variable that already exists. A change made through the second name changes the original variable.

A second name

alias is a reference to score. Setting alias to 95 sets score to 95 as well.

#include <iostream>
#include <vector>

int main() {
  int score = 80;
  int& alias = score;
  alias = 95;
  std::cout << alias << std::endl;
  std::cout << score << std::endl;
  return 0;
}

Changing array elements in place

The range-for uses int&, so each step works on an element itself. Adding 10 changes the array, not a copy.

#include <iostream>
#include <vector>

int main() {
  int prices[3] = {10, 20, 30};
  for (int& price : prices) {
    price += 10;
  }
  for (int price : prices) {
    std::cout << price << std::endl;
  }
  return 0;
}

Example

#include <iostream>
#include <vector>

int main() {
  int prices[3] = {50, 75, 100};
  for (int& price : prices) {
    price += 25;
  }
  for (int price : prices) {
    std::cout << "Price: " << price << std::endl;
  }
  return 0;
}

Key points

  • A reference is declared with & after the type.
  • The declaration names the variable the reference stands for.
  • A reference must be given a variable when it is declared.
  • Writing a new value through a reference writes that value into the original variable.
  • A range-for with int& gives a reference to each element.

In this example, the reference range-for adds 25 to each price in the array. The second loop prints the new prices. Each price is 25 higher than it started.

Note

A reference does not store a copy of the value. It stands for the variable itself.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C++ Compiler

Exercise

score holds 80 and alias is a reference to score. What does score hold after alias = 95?