C++ Identifiers - C++ Programming Tutorial
C++ Course / C++ Basics / C++ Identifiers

C++ Identifiers

BLUF: Mastering C++ Identifiers is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: C++ Identifiers

C++ is renowned for its efficiency. Learn how C++ Identifiers enables low-level control and high-performance computing in the tutorial below.

In the C++ programming language, identifiers play a crucial role in referencing variables, functions, arrays, and custom data types established by the developer. Identifiers serve as fundamental components in programming languages, each with unique guidelines for naming conventions.

Syntax:

It has the following syntax:

Example

// Creating a variable

int x = 15;

int y = 20;

// Creating a function

void func() {}

Here, x and y serve as identifiers. Nevertheless, within a C++ codebase, any term designated by a programmer functions as an identifier. These identifiers are crucial for referencing specific entities at a later stage in the C++ program.

In short, we can say that the C++ identifiers represent the essential elements in a program, which are given below:

  • Constants
  • Variables
  • Functions
  • Labels
  • Defined data types
  • Simple C++ Identifier Example:

Let's examine a sample program showcasing the utilization of identifiers in C++ programming:

Example

Example

#include <iostream>

using namespace std; //using standard namespace

// Must begin with a letter (A-Z or a-z) or an underscore (_)

int studentAge = 20;  

// contain letters, digits (0-9), or underscores (_) after the first character

double salary_2024 = 55000.75;  

// Cannot be a C++ keyword (e.g., 'int', 'return', 'class') - Correct usage

const int MAX_LIMIT = 100;  

//Case-sensitive: 'MyVariable' and 'myVariable' are different

int myVariable = 10;

int MyVariable = 15;  

string employee_Name = "Alice";  

void displayStudentDetails() { 

    cout << "Student Age: " << studentAge << endl;

}

int main() {

    // Displaying variable values

    cout << "Student Age: " << studentAge << endl;

    cout << "Salary: $" << salary_2024 << endl;

    cout << "Max Limit: " << MAX_LIMIT << endl;

    cout << "MyVariable: " << myVariable << endl;

    cout << "MyVariable (capitalized): " << MyVariable << endl;

    cout << "Employee Name: " << employee_Name << endl;

    

    displayStudentDetails(); // Calling function

    return 0;

}

Output:

Output

Student Age: 20

Salary: $55000.75

Max Limit: 100

MyVariable: 10

MyVariable (capitalized): 15

Employee Name: Alice

Student Age: 20

Explanation:

This illustration demonstrates the correct syntax for C++ identifiers, which mandates starting with letters and permitting a mix of letters, numbers, and underscores. It also prohibits the use of keywords and enforces case sensitivity. Variable declarations are done with descriptive names, showcasing values for functions as well as constants.

Rules For C++ Identifiers

Some naming rules for identifiers are common in both C and C++. They are as follows:

  • Only alphabetic characters (A-Z and a-z, digits (0-9), and underscores(_) are allowed.
  • The identifier name cannot start with a digit, i.e., the first letter should be alphabetical. After the first letter, we can use letters, digits, or underscores.
  • In C++, uppercase and lowercase letters are distinct. Therefore, we can say that C++ identifiers are case-sensitive.
  • A declared keyword cannot be used as a variable name.
  • The identifier must not have special elements or spacing within its name, such as my-variable, which fails to meet this rule.
  • A meaningful name system that employs age instead of x works best.
  • Valid Identifiers

The following are examples of valid identifiers:

  • Result
  • Test2
  • _sum
  • power
  • Invalid Identifiers

The following are the examples of invalid identifiers:

  • Sum-1 // containing the special character '-'.
  • 2data //The first letter is a digit.
  • Break// use of a keyword.
  • Note: Identifiers cannot be used as the keywords. It may not conflict with the keywords. We should always use a consistent way to name the identifiers so that our code will be more readable and maintainable.

The primary distinction between C and C++ lies in the restriction on variable name length. ANSI C restricts names to a maximum of 32 characters, whereas ANSI C++ does not impose any restrictions on the length of variable names.

Constants are symbols that represent a fixed value, remaining unchanged throughout program execution. C and C++ both offer different types of literal constants, which are value representations without specific memory addresses. Instances include 123, 12.34, 037, 0X2, and more.

C++ Identifier Example

Let's examine a basic illustration to grasp the idea of identifiers.

Example

Example

#include <iostream>  

using namespace std;  

int main()  

{  

    int a;  

    int A;  	

    cout<<"Enter the values of 'a' and 'A'";  

    cin>>a;  

    cin>>A;  

    cout<<"\nThe values that you have entered are : "<<a<<" , "<<A;  

    return 0;  

}

Output:

Output

Enter the values of 'a' and 'A'

5

6

The values that you have entered are: 5, 6

Explanation:

In the preceding code snippet, we define two variables, 'a' and 'A'. Despite their visual similarity, these letters function as distinct identifiers. Since identifiers are case-sensitive in programming, 'a' and 'A' will be stored in separate memory locations.

Types of Identifiers

In C++, identifiers play a crucial role in various scenarios, including Variables, Functions, and Classes.

1. Variable Identifiers

In C++, programs use variables as labelled storage spaces that contain data values. We have to follow naming rules during declaration, which helps to prevent programming errors.

  • Use camelCase formatting (for constants, use UPPERSNAKECASE).
  • Begin with a lowercase letter.
  • Use clear and descriptive names that reflect their purpose.

C++ Example for Variable Identifiers:

Let's explore an illustration showcasing the utilization of identifiers in Variables.

Example

Example

#include <iostream>

using namespace std; //using standard namespace

int main() {

    int studentAge = 20; // Identifier for a variable

    double piValue = 3.1415; // Identifier for a floating-point variable

    cout << "Student Age: " << studentAge << endl;

    cout << "Value of Pi: " << piValue << endl;

    return 0;

}

Output:

Output

Student Age: 20

Value of Pi: 3.1415

Explanation:

This software comprises of two acceptable identifiers, namely studentAge for integer values and piValue for storing floating-point data.

2. Function Identifiers

In C++, function names serve as markers that distinguish sets of code responsible for specific operations.

  • Opt for camelCase when naming functions.
  • Opt for names based on verbs or actions to convey their functionality.

C++ Function Identifiers Example:

Let's explore a demonstration illustrating the application of identifiers within Functions.

Example

Example

#include <iostream>

using namespace std; //using standard namespace

void displayMessage() { // Function identifier

    cout << "Hello, C++!" << endl;

}

int main() {

    displayMessage() ; // Calling the function identifier

    return 0;

}

Output:

Output

Hello, C++!

Explanation:

In this instance, the displayMessage function acts as a block identifier for code segments that can be reused.

3. Classes Identifiers

When utilizing object-oriented programming, the class identifier sets the framework for program entities.

It is recommended to employ PascalCase, where each word begins with a capital letter.

Additionally, opt for nouns or noun phrases to symbolize objects or entities.

C++ Class Identifier Example:

Let's consider an instance demonstrating the application of identifiers within classes.

Example

Example

#include <iostream>

using namespace std; //using standard namespace

class Car { // Class identifier

public:

    string brand;

    int year;

};

int main() {

    Car myCar; // Object identifier

    myCar.brand = "Toyota";

    myCar.year = 2022;

    cout << myCar.brand << " " << myCar.year << endl;

    return 0;

}

Output:

Output

Toyota 2022

Explanation:

In this instance, the term "Car" serves as a class identifier, while "myCar" acts as an object identifier.

What are the keywords?

Keywords are special reserved terms with a specific significance to the compiler. They serve a distinct purpose and are restricted from being used as identifiers. Instances include 'for', 'break', 'while', 'if', 'else', among others. Predefined words are those whose interpretation is already familiar to the compiler.

Simultaneously, identifiers serve as the labels that programmers assign to various elements within a program, including variables, functions, arrays, objects, and classes.

Differences between Identifiers and Keywords

Several variances between identifiers and keywords in C++ are outlined below:

Identifiers Keywords
Identifiers are the names defined by the programmer to the basic elements of a program. Keywords are the reserved words whose meaning is known by the compiler.
It is used to identify the name of the variable. It is used to specify the type of entity.
It can consist of letters, digits, and underscore. It contains only letters.
It can use both lowercase and uppercase letters. It uses only lowercase letters.
No special character can be used except the underscore. It cannot contain any special character.
The starting letter of identifiers can be lowercase, uppercase or underscore. It can be started only with the lowercase letter.
It can be classified as internal and external identifiers. It cannot be further classified.
Examples are test, result, sum, power, etc. Examples are 'for', 'if', 'else', 'break', etc.

Conclusion

In summary, when programming in C++, it is essential to use identifiers to assign descriptive names to variables, functions, classes, and other elements. Adhering to conventional naming conventions and distinguishing keywords from constants and labels is crucial for generating well-organized and effective C++ source code.

C++ identifiers MCQs:

  1. What is the key difference between an identifier and a keyword in C++?
  • Identifiers come during program development, while keywords serve as end-user definitions.
  • Programmers can modify identifiers but the keywords stay immutable.
  • Identifiers function as programmer-defined names, but keywords exist as predefined elements.
  • Keywords serve as variable names, yet identifiers lack this capability in C++.
  1. Which of the following option is NOT a valid rule for naming identifiers in C++?
  • The first character of identifiers needs to be either a letter or an underscore.
  • Identifiers can contain spaces.
  • Identifiers are case-sensitive.
  • The naming rules for identifiers exclude C++ keywords from being used.
  1. If you attempt to define an identifier using a C++ reserved word, what outcome can be expected?
Example

int return = 10;
  • The program will run normally.
  • The system considers return as any regular variable type.
  • Compilation error due to invalid identifier usage.
  • The program will print 10.
  1. Identify the incorrect identifier among the following:
  • _tempValue
  • 2ndPlayer
  • userName
  • item_count

b) Player 2

  1. What is the expected result of the code snippet provided above?
Example

#include <iostream>

using namespace std;

class Car { // Defining a class named Car  

public:

    string brand; // Public member variable to store the car brand  

};

int main() {

    Car myCar; // Creating an object of the Car class

    myCar.brand = "Tesla"; // Assigning a value to the brand attribute  

    cout << myCar.brand << endl;

    return 0;

}
  • Tesla
  • myCar
  • Compilation error

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience