C++ References and Pointers
A reference is another name for a variable. Passing by reference lets a function change the caller's variable without copying it. Pointers hold addresses and work like in C.
ExampleC++
#include <iostream>
using namespace std;
void addOne(int &x) { x++; }
void addOnePtr(int *p) { (*p)++; }
int main() {
int a = 10;
addOne(a);
cout << a << endl; // 11
addOnePtr(&a);
cout << a << endl; // 12
int &alias = a;
alias = 50;
cout << a << endl; // 50
return 0;
}Output
11 12 50
Quick check
What does passing by reference allow?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.