Introduction to C++ | Identifiers

C++ Identifiers

In C++, an identifier is a name used to identify variables, functions, arrays, classes, and other user-defined objects. Identifiers are essential for referring to the various elements of a program, and they must adhere to specific rules to ensure proper usage.

What is an Identifier?

An identifier is a sequence of characters used to name a program element. In C++, identifiers can be names for variables, functions, classes, constants, etc. Each identifier must begin with a letter (A-Z or a-z) or an underscore (_) and can be followed by letters, digits (0-9), or underscores.

Rules for Identifiers

To be valid in C++, an identifier must follow these rules:

Examples of Valid Identifiers

Here are a few examples of valid identifiers:

Examples of Invalid Identifiers

The following are examples of invalid identifiers in C++:

Code Example: Using Identifiers

Here’s an example of how identifiers are used in a C++ program:

Code Example


                #include <iostream>
                using namespace std;
        
                int main() {
                    // Declaring and initializing valid identifiers
                    int age = 25;
                    double totalAmount = 100.50;
                    string name = "John Doe";
        
                    // Using the identifiers in the program
                    cout << "Name: " << name << endl;
                    cout << "Age: " << age << endl;
                    cout << "Total Amount: $" << totalAmount << endl;
        
                    return 0;
                }
                    

Output

Name: John Doe
Age: 25
Total Amount: $100.5

Pro Tip:

💡 Pro Tip

It's a good practice to follow consistent naming conventions, such as camelCase for variables and functions. This helps improve the readability of your code. Additionally, try to use descriptive names that convey the purpose of the variable or function to make your code easier to understand.