9.x — Chapter 9 summary and quiz
Quick review#
- Every variable has a value and an address.
&xgives the address. - A reference (
int&) is another name for the same variable. - Pass big things by
const&. Use&when a function must change the original. - A pointer (
int*) holds an address.*preaches the value. nullptrmeans "points at nothing". Check before using.- Use smart pointers (
std::unique_ptr) instead ofnew/delete.
Pick an answer. You find out right away if it is right.
After int a { 1 }; int& r { a }; r = 7; what is a?
r is another name for a. Changing r changes a.
What does *p mean when p is a pointer?
* in front of a pointer "follows" it to the box it points at (dereferencing).
Which is the modern, safe way to create a single dynamic object?
std::make_unique gives a std::unique_ptr that frees the memory automatically.
What does this print?
int a { 3 };int& r { a };r = r * 4;std::cout << a;12. r is another name for a, so changing r changes a.
What does this print?
int x { 1 };int y { 2 };int* p { &x };*p = 10;p = &y;*p = 20;std::cout << x << ' ' << y;10 20. First p points at x and sets it to 10. Then it points at y and sets it to 20.
Write a function doubleAll that doubles every number in a std::vector<int>, changing the original list.
void doubleAll(std::vector<int>& v){ for (int& x : v) { x *= 2; }}Two references are needed: one for the parameter (so we change the caller's vector) and one in the loop (so we change the real items).
Tip: press ← / → to move between lessons, / to search.