9.x — Chapter 9 summary and quiz

📘 Chapter 9⏱ about 2 min read✍️ Beginner friendly
Read one box at a time. No rush.

Quick review#

  • Every variable has a value and an address. &x gives 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. *p reaches the value.
  • nullptr means "points at nothing". Check before using.
  • Use smart pointers (std::unique_ptr) instead of new/delete.
Quick check

Pick an answer. You find out right away if it is right.

Quick check #1

After int a { 1 }; int& r { a }; r = 7; what is a?

Quick check #2

What does *p mean when p is a pointer?

Quick check #3

Which is the modern, safe way to create a single dynamic object?

Quiz time
Question #1

What does this print?

C++
int a { 3 };int& r { a };r = r * 4;std::cout << a;

12. r is another name for a, so changing r changes a.

Question #2

What does this print?

C++
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.

Question #3

Write a function doubleAll that doubles every number in a std::vector<int>, changing the original list.

C++
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).

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.