1.8 — Naming things
Read one box at a time. No rush.
Rules for names#
Names for variables (and functions) are called identifiers. The rules:
- Use letters, numbers and underscores
_. - Do not start with a number.
- No spaces.
- Upper and lower case matter.
scoreandScoreare different. - You cannot use C++'s own keywords like
int,returnorif.
C++
int playerScore { 0 }; // okint player_score { 0 }; // okint 2players { 0 }; // error: starts with a numberint my score { 0 }; // error: has a spaceint return { 0 }; // error: return is a keywordGood names#
A good name says what is inside the box.
C++ — wrong ✗
int x { 30 };int tt { 5 };C++ — right ✓
int secondsLeft { 30 };int totalTries { 5 };Good habit
Pick names that explain themselves. secondsLeft is better than s, even though it takes longer to type.
Common styles#
- camelCase:
playerScore— this guide uses this for variables. - snake_case:
player_score— also very common.
Pick one style and stick to it.
Tip: press ← / → to move between lessons, / to search.