C++ Identifers

Definition: C++ identifiers are names used to identify variables, functions, arrays, and other user-defined data types within a C++ program. They play a fundamental role in distinguishing and referencing these elements in code.

Importance: Identifiers help in:

• Declaring variables and constants

• Defining functions and labels

• Creating user-defined data types like classes and structures

Naming Rules:

1. Allowed Characters:

Identifiers can consist of letters (both uppercase and lowercase), digits, and underscores.

2. Starting Character:

An identifier must start with a letter (either uppercase or lowercase) or an underscore (_). It cannot start with a digit.

3. Case Sensitivity:

Identifiers in C++ are case-sensitive. This means that variable, Variable, and VARIABLE are considered different identifiers.

4. Keywords:

C++ keywords, which are reserved words with special meanings, cannot be used as identifiers. For example, int, return, and if are reserved and cannot be used as names for variables or functions.

Examples of Identifiers:

• totalSum

• calculateArea

• userInput

• MAX_VALUE

• array1

Examples of Invalid Identifiers:

• 1stVariable (cannot start with a digit)

• total-Sum (contains invalid character -)

• int (keyword and cannot be used as an identifier)

Example for Identifiers:

#include <iostream>
using namespace std;

int main() {
    // Variable declarations
    int num1; // Identifier for an integer variable
    int Num1; // Another identifier for an integer variable (case-sensitive)

    // Prompt user for input
    cout << "Enter the value for 'num1': ";
    cin >> num1; // Read user input into num1

    cout << "Enter the value for 'Num1': ";
    cin >> Num1; // Read user input into Num1

    // Output the values entered
    cout << "<br>The values that you have entered are: " << num1 << " and " << Num1 << endl;

    return 0;
}

Output:

Enter the value for 'num1': 10
Enter the value for 'Num1': 20

The values that you have entered are: 10 and 20

Differences between Identifiers and Keywords

Attribute Identifiers Keywords
Definition Names defined by the programmer for variables, functions, etc. Reserved words with special meaning to the compiler
Usage Used to name program elements (variables, functions, etc.) Used to specify the type or control the structure of the program
Composition Can include letters, digits, and underscores Consist only of letters (lowercase)
Case-Sensitivity Case-sensitive (e.g., Variable vs. variable) Generally lowercase and not case-sensitive
Special Characters Only underscores allowed No special characters allowed
Starting Character Can start with a letter or underscore Must start with a letter (lowercase)
Classification Can be internal or external Not classified into further categories
Examples myVar, totalSum, calculateArea if, while, return, break