Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Keywords are an essential part of any programming language. These are like the predefined set of rules or reserved keywords that we have in our daily spoken languages. They play a crucial role in defining the structure and functionality of code. C++ has a set of reserved words that have special meanings and purposes within the language. These keywords cannot be used as identifiers, like variable or function names, as they are predefined by the language itself. This concept of keywords is very important for writing valid and effective C++ code.
In this article, we will discuss what keywords are, the rules for naming identifiers, examples of good and bad identifiers, and how keywords differ from identifiers.
Token
In C++, a token is the smallest unit of the program that the compiler can understand & process. It is a sequence of characters that represents a single element of the language, such as a keyword, identifier, literal, or operator. Tokens are the building blocks of a C++ program, & the compiler reads the source code as a stream of tokens during the compilation process.
Let’s take a look at a few examples of tokens:
Keywords: `int`, `float`, `if`, `else`, `while`, etc.
Identifiers: Variable names, function names, etc.
Literals: Integer constants, floating-point constants, character constants, string literals, etc.
The compiler analyzes each token to determine its meaning and role within the program. It checks for syntax errors and applies the language rules to ensure that the tokens are used correctly.
What is an identifier?
An identifier is a name given to a program element, such as a variable, function, class, or object. It is used to uniquely identify and refer to that element throughout the program. In C++, identifiers are user-defined names that follow certain rules and conventions. They are created by the programmer to represent specific entities in the code.
For example:
int age; // "age" is an identifier for an integer variable
float calculateAverage(float a, float b); // "calculateAverage" is an identifier for a function
class Student; // "Student" is an identifier for a class
Identifiers help make the code more readable, meaningful, and maintainable. They provide a way to associate a descriptive name with a program element, making it easier to understand its purpose and usage. The choice of identifiers is important, as they should clearly convey the intent and functionality of the associated program element.
Rules for naming identifiers
In C++, there are certain rules that must be followed when choosing identifiers for variables, functions, classes, or other program elements. These rules ensure that the identifiers are valid & conform to the language standards. The main rules for naming identifiers in C++ are:
1. Identifiers can only contain letters (a-z, A-Z), digits (0-9), & underscores (_).
2. The first character of an identifier must be a letter or an underscore. It cannot be a digit.
3. Identifiers are case-sensitive, meaning that "myVariable" & "myvariable" are considered different identifiers.
4. Keywords (reserved words) cannot be used as identifiers.
5. Identifiers should be descriptive & meaningful, indicating the purpose or content of the program element they represent.
6. Identifiers cannot contain whitespace characters, such as spaces or tabs.
7. There is no specific length limit for identifiers, but it is recommended to keep them concise yet descriptive.
Examples of valid identifiers
int count;
float average_score;
char _flag;
bool isReady;
Examples of invalid identifiers
int 1stNumber; // Cannot start with a digit
float my variable; // Contains whitespace
char if; // "if" is a keyword
If you follow these rules, it will help us write code that is syntactically correct and self-explanatory. It will also promote good programming practices and enhance code readability.
Examples of good & bad identifiers
Choosing appropriate identifiers is crucial for writing clean, readable, and maintainable code. Let’s look at the some examples of good and bad identifiers:
Good identifiers
int numStudents; // Clear and descriptive
float averageScore; // Uses camelCase convention
const int MAX_SIZE = 100; // Uses uppercase for constants
bool is_valid; // Underscore separates words
void calculateTotal(); // Verb-noun combination for functions
Good identifiers are descriptive, meaningful, and follow consistent naming conventions. They provide clarity about the purpose or content of the program element they represent.
Some of the common naming conventions which are famous and useful are:
camelCase: Each word except the first starts with a capital letter (e.g., `firstName`).
PascalCase: Each word starts with a capital letter (e.g., `StudentRecord`).
snake_case: Words are separated by underscores (e.g., `total_count`).
Bad identifiers
int x; // Single-letter identifier, not descriptive
float a1, a2, a3; // Numbered identifiers, not meaningful
char _; // Single underscore, not allowed
bool flag; // Generic name, doesn't convey specific purpose
void func(); // Abbreviation, not descriptive
Bad identifiers are often too short, ambiguous, or not descriptive enough. They make the code harder to understand and maintain. Single-letter identifiers, numbered identifiers, or generic names like "flag" or "func" should be avoided. Identifiers should be chosen thoughtfully to convey the intended meaning and purpose of the program element.
How are keywords different from identifiers?
Keywords
Identifiers
Keywords are predefined words in C++ that have special meanings and purposes within the language.
Identifiers are user-defined names given to variables, functions, classes, or other program elements.
Keywords are part of the C++ language syntax and cannot be used as identifiers.
Identifiers are created by the programmer to represent specific entities in the code.
Keywords have fixed spellings and cannot be modified.
Identifiers can be chosen by the programmer, following the naming rules.
Examples of keywords include int, float, if, else, while, class, public, etc.
Examples of identifiers include variable names like count, function names like calculateAverage, and class names like Student.
Keywords are case-sensitive and must be written in lowercase.
Identifiers are case-sensitive, and the programmer can choose the casing convention (e.g., camelCase, PascalCase, snake_case).
The number of keywords in C++ is fixed and predefined by the language.
There is no limit to the number of identifiers a programmer can create in a program.
Keywords have specific purposes and are used to define the structure, behavior, and functionality of the program.
Identifiers are used to give meaningful names to program elements, making the code more readable and maintainable.
Example
#include <iostream>
using namespace std;
int main() {
int age = 25;
string name = "Rahul";
if (age >= 18) {
cout << name << " is an adult." << endl;
} else {
cout << name << " is a minor." << endl;
}
return 0;
}
You can also try this code with Online C++ Compiler
`int`, `using`, `namespace`, `if`, `else`, and `return` are keywords. They have predefined meanings in C++ and are used to define the structure and behavior of the program.
`main`, `age`, `name`, `cout`, `endl`, and `std` are identifiers. They are user-defined names chosen by the programmer to represent specific entities in the code.
`main` is an identifier for the main function.
`age` and `name` are identifiers for variables.
`cout` and `endl` are identifiers for output stream objects.
`std` is an identifier for the standard namespace.
The keywords `int` and `string` are used to declare variables `age` and `name`, respectively. The keyword `if` is used to create a conditional statement that checks if `age` is greater than or equal to 18. The keywords `else` and `return` are used for control flow and returning a value from the `main` function.
This example clearly shows how keywords and identifiers work together to create a functional C++ program. The keywords provide language-specific functionality, while the identifiers allow the programmer to give meaningful names to the program elements.
Frequently Asked Questions
Can I use a keyword as an identifier in C++?
No, keywords are reserved words in C++ and cannot be used as identifiers.
Are identifiers case-sensitive in C++?
Yes, identifiers in C++ are case-sensitive. For example, "myVar" and "myvar" are considered different identifiers.
Is there a limit to the length of an identifier in C++?
There is no specific length limit for identifiers in C++, but it is recommended to keep them concise yet descriptive.
Conclusion
In this article, we discussed the concept of keywords and identifiers in C++. We learned that keywords are predefined words with special meanings, while identifiers are user-defined names for program elements. We also learned the rules for naming identifiers, provided examples of good and bad identifiers, and highlighted the differences between keywords and identifiers.