C++ Identifiers
Understanding Identifiers
Identifiers are names used for variables, functions, classes, objects, and other program elements. They act as labels that make code easier to read, understand, and maintain.
Choosing clear and meaningful identifiers is essential for writing clean, maintainable code that is easy to debug.
Identifier Rules
C++ enforces specific rules for valid identifiers:
// Examples shown in block scope to avoid global-reservation pitfalls
void demo() {
int age; // Valid
int _score; // Valid here (local). Avoid leading underscores at namespace/global scope.
int user2; // Valid
// int 2ndPlace; // Invalid: cannot start with a digit
// int user name; // Invalid: spaces are not allowed
// int double; // Invalid: reserved keyword
}
Reserved Identifiers & Portability
Certain names are reserved for the implementation and must not be used in your code:
- Any identifier containing two consecutive underscores (e.g., my__impl) is reserved.
- Any identifier that begins with an underscore followed by an uppercase letter (e.g., _Vector) is reserved in any scope.
- Any identifier that begins with a single underscore is reserved at namespace/global scope.
- Some compilers allow characters like '$' in identifiers, but this is non-standard—avoid for portable code.
Case & Character Notes
Identifiers are case-sensitive and unlimited in length (practically constrained by tools).
Stick to ASCII letters, digits, and underscores for portability. While C++ permits certain Unicode in identifiers via universal character names, cross-tooling support varies; avoid unless you know your toolchain supports it.
Naming Conventions
Common naming styles in C++ include:
- camelCase: studentCount
, totalAmount
- snake_case: student_count
, total_amount
- PascalCase: StudentCount
(commonly used for class names)
- UPPER_CASE: MAX_SIZE
(commonly used for macros and constants)
Best Practices
- Use descriptive names that show intent (numStudents
is better than n
)
- Keep names concise but not cryptic (numberOfStudents
is better than numberOfStudentsInTheComputerScienceDepartment
)
- Stay consistent with abbreviations (num
or number
, but not both)
- Avoid single-letter names, except for simple loop counters (i
, j
)
- Differentiate related names meaningfully (totalPrice
vs netPrice
)
// Clear and descriptive
int studentCount;
double averageScore;
bool isActive;
// Ambiguous or unclear
int sc;
double as;
bool a;