In the realm of programming, keywords and identifiers are fundamental building blocks that help structure your code. Keywords are reserved words with specific meanings in C++, while identifiers are names used to identify variables, functions, classes, etc. Understanding these concepts is crucial for writing clear, error-free, and maintainable C++ programs.
Keywords are predefined words in the C++ language that have special meaning and cannot be used as identifiers (names for variables, functions, etc.). Identifiers, on the other hand, are user-defined names that help you identify different parts of your program. Knowing the rules for using keywords and how to name identifiers properly will make your code more readable and less prone to errors.
In this tutorial, we'll explore:
C++ reserves a set of keywords that have specific meanings within the language. These keywords cannot be used as identifiers (variable names, function names, etc.). Here is a list of some common C++ keywords:
| Keyword | Description |
|---|---|
auto | Used for automatic type deduction. |
break | Exits a loop or switch statement. |
case | Used in switch statements to specify cases. |
char | Represents character data. |
class | Defines a class. |
const | Declares constants. |
continue | Skips the current iteration of a loop and continues with the next one. |
default | Used in switch statements to specify a default case. |
delete | Deletes an object or array. |
do | Starts a do-while loop. |
double | Represents double-precision floating-point numbers. |
else | Used with if statements to handle alternative cases. |
enum | Defines enumerations. |
explicit | Prevents implicit type conversions. |
export | Used in template definitions (deprecated). |
extern | Declares a variable or function that is defined elsewhere. |
false | Represents the boolean value false. |
float | Represents single-precision floating-point numbers. |
for | Starts a for loop. |
friend | Grants special access rights to classes and functions. |
goto | Jumps to a labeled statement (generally discouraged). |
if | Starts an if statement. |
inline | Suggests that the function should be inlined by the compiler. |
int | Represents integer data. |
long | Represents long integers. |
mutable | Allows modification of a member variable even if it's declared const. |
namespace | Defines a namespace for organizing code. |
new | Allocates memory for an object or array. |
nullptr | Represents a null pointer (C++11 and later). |
operator | Overloads operators. |
private | Restricts access to class members. |
protected | Allows access within the class and derived classes. |
public | Allows access from anywhere. |
register | Suggests that a variable should be stored in a register (deprecated). |
return | Returns a value from a function. |
short | Represents short integers. |
signed | Indicates signed integer data. |
sizeof | Returns the size of a type or object. |
static | Declares static variables, functions, and members. |
struct | Defines a structure. |
switch | Starts a switch statement. |
template | Used for template metaprogramming. |
this | Points to the current object. |
throw | Throws an exception. |
true | Represents the boolean value true. |
try | Starts a try block. |
typedef | Creates type definitions. |
typeid | Returns the runtime type information of an object. |
typename | Used in template declarations. |
union | Defines a union. |
unsigned | Indicates unsigned integer data. |
using | Alias for namespaces and templates (C++11). |
virtual | Declares virtual functions. |
void | Represents no type or void return value. |
volatile | Indicates that a variable can be changed by external factors. |
while | Starts a while loop. |
Warning
Identifiers in C++ must follow certain rules:
Start with a Letter or Underscore: The first character of an identifier can be a letter (a-z, A-Z) or an underscore (_). It cannot start with a digit.
Followed by Letters, Digits, or Underscores: Subsequent characters can include letters, digits (0-9), and underscores.
Case Sensitivity: Identifiers are case-sensitive. myVariable and MyVariable are considered different identifiers.
Reserved Keywords: Identifiers cannot be the same as any C++ reserved keyword.
No Spaces or Special Characters: Identifiers cannot contain spaces or special characters like @, #, $, etc.
Maximum Length: While there is no strict limit, identifiers should be reasonably short for readability and maintainability.
Here are some valid and invalid identifier examples:
1#include <iostream>23int main() {4int myVariable = 10;5double _pi = 3.14;6bool is_valid = true;7std::cout << "Valid identifiers work!" << std::endl;8return 0;9}
Valid identifiers work!
1#include <iostream>23int main() {4int 1variable = 10; // Invalid: starts with a digit5double my-variable = 3.14; // Invalid: contains a hyphen6bool @isValid = true; // Invalid: starts with an '@'7std::cout << "Invalid identifiers cause errors!" << std::endl;8return 0;9}
$ g++ invalid_identifiers.cpp -o invalid_identifiersinvalid_identifiers.cpp: In function ‘int main()’:invalid_identifiers.cpp:4:7: error: expected identifier before numeric constantint 1variable = 10; // Invalid: starts with a digit^invalid_identifiers.cpp:5:13: error: expected unqualified-id before '-' tokendouble my-variable = 3.14; // Invalid: contains a hyphen^invalid_identifiers.cpp:6:12: error: expected identifier before '@' tokenbool @isValid = true; // Invalid: starts with an '@'^
While C++ allows a wide range of identifiers, following certain naming conventions can make your code more readable and maintainable:
Use Descriptive Names: Choose names that clearly describe the purpose or function of the identifier.
Camel Case for Variables and Functions: Start with a lowercase letter and capitalize the first letter of each subsequent word.
calculateTotalPricePascal Case for Classes and Structs: Capitalize the first letter of each word, including the first one.
CustomerOrderUse Uppercase Letters for Macros and Constants: This distinguishes them from regular variables.
MAX_VALUEAvoid Abbreviations: Use full words unless they are widely understood abbreviations (e.g., ID for Identifier).
Consistent Naming Style: Stick to a consistent naming style throughout your codebase.
Here's an example demonstrating these conventions:
1#include <iostream>23class CustomerOrder {4public:5void calculateTotalPrice() {6int itemCount = 5;7double itemPrice = 2.99;8double totalPrice = itemCount * itemPrice;9std::cout << "Total Price: $" << totalPrice << std::endl;10}11};1213int main() {14CustomerOrder order;15order.calculateTotalPrice();16return 0;17}
Total Price: $14.95
Tip
Let's create a simple program that calculates the area of a rectangle using descriptive variable names and follows naming conventions:
1#include <iostream>23class Rectangle {4public:5void calculateArea() {6double length = 10.5;7double width = 7.2;8double area = length * width;9std::cout << "The area of the rectangle is: " << area << " square units." << std::endl;10}11};1213int main() {14Rectangle rect;15rect.calculateArea();16return 0;17}
The area of the rectangle is: 75.6 square units.
Now that you have a solid understanding of keywords and identifiers, the next step is to learn about Variables, Literals, Constants & Storage Classes. These concepts will help you declare and manipulate data in your C++ programs. Stay tuned!
Note