Lesson 26 +10 XP

C++ Identifiers

C++ Identifiers

Every name you invent in C++ - for a variable, a function, a class - is called an identifier. There are rules about what counts as a valid one.

The naming rules

An identifier must follow these laws:

  • Can use letters (a to z, A to Z), digits (0 to 9), and the underscore _.
  • Cannot start with a digit. 1value is illegal; value1 is fine.
  • Cannot contain spaces or most punctuation (-, +, ?, etc. are all banned).
  • Cannot be a keyword of the language (like int, if, return).
  • Case-sensitive: Score and score are two different names.

Valid vs invalid

int myNumber;      // good
int _temp;         // good (though names starting with _ have special rules)
int value2;        // good
int 2value;        // BAD: starts with a digit
int my-number;     // BAD: dash is not allowed
int int;           // BAD: int is a keyword

Best practices

  • Use descriptive names that say what the variable holds: maxSpeed, not m.
  • Start variable names with a lowercase letter; start type names with uppercase.
  • Use camelCase for multi-word names: playerHealth.
  • Common styles: snake_case (words joined by underscores) is also popular.
  • Be consistent - pick a style and keep it.

Reserved keywords

A keyword is a word the language keeps for itself. You cannot reuse them as names. Some examples:

int, if, else, for, while, return, class, void, const, break, case

If you try int if = 5;, the compiler complains - if is spoken for.

TL;DR

  • Identifiers use letters, digits, and _; they can't start with a digit.
  • No spaces, no punctuation like -, no keywords.
  • C++ is case-sensitive: Score != score.
  • Prefer clear, descriptive, consistent names.