References

References

A reference variable is an alias for another object. It is created using the & sign.

Two things to note:

  • Anything done to the reference also happens to the original.
  • Aliases cannot be changed to alias something else.

Syntax

int &sonny = songqiao;

Pass-By-Reference

In C++, pass-by-reference refers to passing parameters to a function by using references.

It allows the ability to:

  • Modify the value of the function arguments.
  • Avoid making copies of a variable/object for performance reasons.
void swap_num(int &i, int &j) {
int temp = i;
i = j;
j = temp;
}
int main() {
int a = 100;
int b = 200;
swap_num(a, b);
std::cout << "A is " << a << "\n";
std::cout << "B is " << b << "\n";
}

const Reference

In C++, pass-by-reference with const can be used for a function where the parameter(s) won’t change inside the function.

This saves the computational cost of making a copy of the argument.

int triple(int const &i) {
return i * 3;
}
Edit this page on GitHub

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your feedback.

Learn C++ on Codecademy

Edit this page on GitHub

Contributors