Home C++ Identifiers in C++ tutorial with code examples

Identifiers in C++ tutorial with code examples

In C++, identifiers are names given to various entities such as variables, functions, arrays, classes, and objects.

Identifiers make it possible to refer to these entities in code, allowing us to work with data and logic through meaningful names.

Identifiers must follow specific naming rules and conventions to ensure they are valid and clear.

Rules for Identifiers in C++

  1. Allowed Characters: Identifiers can contain letters (A-Z, a-z), digits (0-9), and underscores (_).
  2. No Starting with a Digit: Identifiers cannot start with a digit.
  3. No Special Characters: Symbols like @, $, %, and others are not allowed.
  4. Case-sensitive: Identifiers are case-sensitive, so MyVariable and myvariable are considered different.
  5. No Reserved Keywords: Identifiers cannot use keywords like int, return, class, etc., which are reserved by the language.

Let’s go through examples to understand how to create and use identifiers effectively in C++.

1. Basic Identifiers for Variables

Variables are named entities that store values in C++. Following naming rules, we can create identifiers for variables.

#include <iostream>
using namespace std;

int main() {
    int age = 25;        // Valid identifier
    double salary = 5000.50; // Valid identifier

    cout << "Age: " << age << endl;
    cout << "Salary: $" << salary << endl;

    return 0;
}

Explanation:

  • age and salary are identifiers for variables storing integer and double values, respectively.
  • The identifier names are meaningful, indicating the purpose of the variables.

Output:

Age: 25
Salary: $5000.5

2. Using Identifiers for Functions

Identifiers are also used to name functions, which encapsulate specific blocks of code for reuse.

#include <iostream>
using namespace std;

// Function identifier: addNumbers
int addNumbers(int a, int b) {
    return a + b;
}

int main() {
    int result = addNumbers(5, 10); // Using the function identifier
    cout << "Sum: " << result << endl;

    return 0;
}

Explanation:

  • addNumbers is the identifier for a function that takes two integers and returns their sum.
  • The function is then called in main using the identifier addNumbers.

Output:

Sum: 15

3. Naming Conventions for Readability

Although C++ doesn’t enforce naming conventions, it’s a best practice to use descriptive and readable names. Common naming conventions include:

  • Camel Case: camelCaseVariable
  • Pascal Case: PascalCaseFunction
  • Snake Case: snake_case_variable
#include <iostream>
using namespace std;

int main() {
    int userAge = 30;             // Camel case
    double MonthlySalary = 4000.0; // Pascal case
    int employee_id = 101;         // Snake case

    cout << "User Age: " << userAge << endl;
    cout << "Monthly Salary: $" << MonthlySalary << endl;
    cout << "Employee ID: " << employee_id << endl;

    return 0;
}

Output:

User Age: 30
Monthly Salary: $4000
Employee ID: 101

4. Identifiers for Classes and Objects

Identifiers name classes and objects in object-oriented programming, allowing us to create and manipulate instances of classes.

#include <iostream>
using namespace std;

// Class identifier: Person
class Person {
public:
    string name;
    int age;

    void displayInfo() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

int main() {
    Person person1; // Object identifier
    person1.name = "Alice";
    person1.age = 25;

    person1.displayInfo();

    return 0;
}

Explanation:

  • Person is the identifier for a class that represents a person.
  • person1 is an object of type Person.

Output:

Name: Alice, Age: 25

5. Case-Sensitivity in Identifiers

Identifiers in C++ are case-sensitive, meaning MyVar and myvar are different identifiers.

#include <iostream>
using namespace std;

int main() {
    int myVar = 10;  // Identifier 'myVar'
    int MyVar = 20;  // Identifier 'MyVar'

    cout << "myVar: " << myVar << endl;
    cout << "MyVar: " << MyVar << endl;

    return 0;
}

Explanation:

  • myVar and MyVar are treated as different identifiers because of case sensitivity.
  • This can help create distinct variable names but can also lead to confusion if not used carefully.

Output:

myVar: 10
MyVar: 20

6. Identifiers with Special Characters (Underscore)

The underscore (_) can be used in identifiers to improve readability, especially for longer names.

#include <iostream>
using namespace std;

int main() {
    int total_price = 100;  // Using underscores for readability
    int discount_rate = 5;

    cout << "Total Price: $" << total_price << endl;
    cout << "Discount Rate: " << discount_rate << "%" << endl;

    return 0;
}

Explanation:

  • Identifiers like total_price and discount_rate use underscores to improve readability.

Output:

Total Price: $100
Discount Rate: 5%

7. Invalid Identifiers

Identifiers that don’t follow C++ naming rules are considered invalid and will cause compilation errors.

#include <iostream>
using namespace std;

int main() {
    // int 1stNumber = 5;   // Invalid: Starts with a digit
    // int @rate = 10;      // Invalid: Contains a special character '@'
    // int int = 20;        // Invalid: Uses a reserved keyword 'int'

    int firstNumber = 5;    // Valid
    int rate = 10;          // Valid

    cout << "First Number: " << firstNumber << endl;
    cout << "Rate: " << rate << endl;

    return 0;
}

Explanation:

  • Examples of invalid identifiers are commented out to avoid compilation errors:
    • 1stNumber: starts with a digit.
    • @rate: contains a special character (@).
    • int: uses a reserved keyword.

8. Using Identifiers with Constants

Constants use const in C++ and typically follow a naming convention with all uppercase letters and underscores.

#include <iostream>
using namespace std;

int main() {
    const double PI = 3.14159;          // Constant identifier in uppercase
    const int MAX_SCORE = 100;          // Using uppercase for readability

    cout << "Value of PI: " << PI << endl;
    cout << "Maximum Score: " << MAX_SCORE << endl;

    return 0;
}

Explanation:

  • PI and MAX_SCORE are identifiers for constants, using uppercase letters for readability.

Output:

Value of PI: 3.14159
Maximum Score: 100

9. Scope-Specific Identifiers

C++ allows identifiers to be specific to different scopes (e.g., local and global scope).

#include <iostream>
using namespace std;

int number = 100; // Global scope

int main() {
    int number = 50; // Local scope (shadows the global variable)
    
    cout << "Local number: " << number << endl;
    cout << "Global number: " << ::number << endl; // Accessing global scope with ::

    return 0;
}

Explanation:

  • number is defined globally with a value of 100.
  • Another number in main is a local identifier that shadows the global one.
  • ::number accesses the global number variable.

Output:

Local number: 50
Global number: 100

10. Identifiers in Loops

Identifiers are commonly used in loops to define control variables and counters.

#include <iostream>
using namespace std;

int main() {
    // Loop variable identifier: i
    for (int i = 0; i < 5; i++) {
        cout << "Loop iteration: " << i << endl;
    }

    return 0;
}

Explanation:

  • i is an identifier for the loop variable in a for loop.
  • Using simple and consistent identifiers like i, j, or k in loops is a common convention.

Output:

Loop iteration: 0
Loop iteration: 1
Loop iteration: 2
Loop iteration: 3
Loop iteration: 4

11. Using Descriptive Identifiers for Readability

Using descriptive identifiers makes code more understandable, especially in larger codebases.

#include <iostream>
using namespace std;

int main() {
    int numberOfStudents = 25;      // Descriptive identifier
    int numberOfClasses = 

5;

    cout << "Number of Students: " << numberOfStudents << endl;
    cout << "Number of Classes: " << numberOfClasses << endl;

    return 0;
}

Explanation:

  • Descriptive identifiers like numberOfStudents and numberOfClasses improve readability by conveying the purpose of the variables.

Output:

Number of Students: 25
Number of Classes: 5

Summary Table of Identifier Rules and Conventions

Type Example Description
Variable int age; Stores data, following naming rules
Function int addNumbers(); Used to encapsulate reusable code
Class class Person {} Names classes, usually in Pascal case
Constant const double PI; Typically in uppercase with underscores
Loop Variable for (int i = 0;…) Controls loop execution
Descriptive Naming int numberOfStudents; Increases readability
Scope-Specific ::number Accesses global or specific scope variables

Key Takeaways

  • Identifiers are used to name variables, functions, classes, constants, and more.
  • Follow C++ rules and conventions to make identifiers meaningful, unique, and easy to read.
  • Avoid reserved keywords and use consistent naming conventions to improve code readability.

You may also like