C++ Identifiers and Keywords with Examples

In this article, you will learn about "identifiers" and "keywords," the two most important topics when discussing C++ programming. So, without further ado, let us start with the identifiers.

What are identifiers?

Identifiers are the basic building blocks of a program. Identifiers are used as a general name given to different parts of the program, namely variables, objects, classes, functions, arrays, etc.

Since C++ is a case-sensitive language, therefore, "fresherearth,"  "fresherearth,"  "fresherearth,"  and "fresherearth" are all four different identifiers.

Before moving further, let's first understand the rules for creating an identifier in C++.

Rules to create or name an identifier in C++

To create an identifier in the C++ language, you need to follow the following rules:

Following is a list of some valid identifiers. This list is included for your convenience because examples help to make the topic more understandable.

Tip: You may either use underscore in variable names to separate parts of the name, such as last_name, first_name, and main_balance, or you may go for "capital style" notation, such as lastName, firstName, and mainBalance, i.e., capitalizing the first letter of the next word.

C++ Identifiers Example

The following C++ program is an example program of C++ identifiers that will give you an idea of how identifiers are used in C++ programming:

#include<iostream>
using namespace std;
int main()
{
   char ch;
   char name[20];
   int num;

   cout<<"Enter a character: ";
   cin>>ch;
   cout<<"You entered: "<<ch<<endl;

   cout<<"\nEnter your name: ";
   cin>>name;
   cout<<"Your name is: "<<name<<endl;

   cout<<"\nEnter a number: ";
   cin>>num;
   cout<<"You entered: "<<num<<endl;

   return 0;
}

When the above C++ program is compiled and executed, it will produce the following output:

c++ identifiers

Now supply the input, say "c," as a character, and hit the "ENTER" key. Then supply another input, say "fresherearth," as a name, and again hit the "ENTER" key. The following snapshot shows the sample run of the above C++ example program.

c++ identifiers example

The cout<<endl; and cout<<"\n"; both insert a line break on the output console. You can refer to "endl" as "end-line."

Keywords in C++

To a language compiler, certain words have a heightened significance, and these are known as keywords. Because these are reserved words that are used for specific purposes, you are not allowed to use them as regular identifier names.

I previously stated that reserved words or keywords may not be used as identifiers. As a result, it is critical to remember the list of keywords so that you do not accidentally use them as identifiers. As C++ keywords, keep the following list in mind:

More Examples

C++ Quiz


« Previous Tutorial Next Tutorial »