In C++ programming, identifiers are unique names given to variables,
functions, classes, structures, and other elements in a program. For example,
in the following statement:
int num = 11;
`num` is an identifier.
Rules for Naming Identifiers in C++
You can use any word as an identifier if it follows these rules:
1. Allowed Characters: Identifiers can include letters (A-Z or a-z),
digits (0-9), and underscores (_). Special characters and spaces are not
allowed.
2. Starting Character: An identifier must start with a letter or an
underscore.
3. Reserved Keywords: Some words in C++ are reserved for specific
purposes, so you can't use them as identifiers. For example, `int` is a
keyword and can't be used as an identifier.
4. Uniqueness: Each identifier must be unique within its scope.
5. Case Sensitivity: C++ is case-sensitive, so `Num` and `num` are
considered different identifiers.
Here are some examples of valid and invalid identifiers:
Valid: `studentAge`, `_accountBalance`, `Car24`
Invalid: `2ndStudent` (starts with a digit), `total#sum`
(contains a special character)
The below images show some valid and invalid C++ identifiers.
Example of C++ Identifiers
Below is an example of a C++ program that uses identifiers correctly:
#include <iostream> using namespace std; // The Car_24 identifier is used to name the class class Car_24 { string Brand; string model; int year; }; // The calculateSum identifier is used to name the function void calculateSum(int a, int b) { int _sum = a + b; cout << "The sum is: " << _sum << endl; } int main() { // Identifiers used as variable names int studentAge = 20; double accountBalance = 1000.50; string student_Name = "Karan"; calculateSum(2, 10); return 0; }
Output:
The sum is: 12
Additional Tips
- Consistency: Use meaningful names for identifiers to make your code more readable and maintainable. For example, instead of using `a` and `b`, use `firstNumber` and `secondNumber`.
- Practice: Regularly write and review code to familiarize yourself with identifier rules and improve your coding habits.
- Resources: Utilize online tutorials, coding platforms, and communities to learn and get feedback on your code.
By following these guidelines, you'll write cleaner, more efficient code that
adheres to best practices in C++ programming.