7.3 — The most common mistakes
Read one box at a time. No rush.
A checklist. When something's wrong, scan this list first.
Syntax slips#
- Missing
;at the end of a statement. - Missing
}— every{needs a partner. - Using
'for text instead of". - Writing
coutwithoutstd::. - Forgetting
#include <string>or another header.
Logic slips#
=instead of==in a condition.- A
;right afterif (...)orwhile (...). int / intthrowing away decimals.- Using a variable before giving it a value.
- A loop that never ends (forgot
++i). - Off-by-one:
<=where you meant<(or the other way round).
The off-by-one error#
This is so common it has its own name.
C++ — wrong ✗
// meant to print 5 starsfor (int i { 0 }; i <= 5; ++i) std::cout << '*'; // prints 6!C++ — right ✓
for (int i { 0 }; i < 5; ++i) std::cout << '*'; // prints 5Tip
Test your loops with tiny numbers. Does it work for 0? For 1? Then it probably works for 1000.
Tip: press ← / → to move between lessons, / to search.