References & Pointers
Programming Languages · C++ Going Further · 12 min
Give a variable a second name, let functions change your variables, and meet pointers gently.
A second name
A reference is a second name for a variable that already exists. Put & after the type. Change the nickname and the original changes too, because they are the same box:
int score = 5;
int& points = score;
points = 8;
std::cout << score << "\n"; // 8
Make an
intreference calledreftolives.Set
refto9, then printlives.
Copies vs. the real thing
Normally a function gets a copy of what you pass in. In the editor, addTen changes its copy, the copy is thrown away, and score stays 5. Run it and see.
Make the parameter a reference, int& n, and the function works on the real score instead.
Change the parameter to
int& nso the program prints15.
Addresses and pointers
Every variable lives at an address in memory, like a house number. &age gives you that address. A pointer is a variable that stores an address. Its type has a star: int*.
Put * in front of a pointer to read the value at that address:
int x = 4;
int* p = &x;
std::cout << *p << "\n"; // 4
Create a pointer
int* pthat holds the address ofage.Print the value
ppoints to, using*p.
Changing through a pointer
*p isn't just for reading. Assign to it and you change the variable it points to:
int x = 4;
int* p = &x;
*p = 7;
std::cout << x << "\n"; // 7
Use
pto settempto25.
Put it together: swap
Write a function that swaps two variables. It needs references, or it would only swap copies.
To swap, park one value in a spare variable first:
int temp = a;
a = b;
b = temp;
Write
void swapValues(int& a, int& b)that swaps the two values.Call
swapValues(x, y)inmainso it printsx = 2, y = 1.