Loading lessons...
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 (
atoz,AtoZ), digits (0to9), and the underscore_. - Cannot start with a digit.
1valueis illegal;value1is fine. - Cannot contain spaces or most punctuation (
-,+,?, etc. are all banned). - Cannot be a keyword of the language (like
int,if,return). - Case-sensitive:
Scoreandscoreare 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, notm. - 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.