C++ Keywords and Identifiers


Introduction

In C++, keywords and identifiers are fundamental concepts that govern the structure of the language. Understanding them is essential for writing syntactically correct and readable C++ code.

  • Keywords are reserved words that have special meanings in C++. These cannot be used as names for variables, functions, or any other user-defined entities.
  • Identifiers are names given to various program elements like variables, functions, classes, and more. These names help identify different entities within a C++ program.

In this blog post, we’ll explore both keywords and identifiers in detail, including their rules and examples to help you better understand how to use them in your programs.


What Are C++ Keywords?

Keywords in C++ are predefined, reserved words that the C++ compiler uses to perform specific tasks. Keywords have a special meaning in the C++ language, and you cannot use them as identifiers (e.g., variable names, function names, etc.).

There are 95 reserved keywords in C++ (as of C++11, including nullptr and other newer keywords). These words are the building blocks of the C++ language and include things like data types, control structures, and function definitions.

Common C++ Keywords

Here are some of the most common keywords in C++:

  • int: Defines an integer data type.
  • float: Defines a floating-point number data type.
  • char: Defines a character data type.
  • void: Specifies that a function does not return a value.
  • if, else, switch: Conditional statements for decision making.
  • for, while, do: Loop control structures.
  • return: Exits from a function and optionally returns a value.
  • class, struct: Used for defining user-defined data types.
  • public, private, protected: Access specifiers in classes.
  • new, delete: Memory management keywords for dynamic memory allocation and deallocation.
  • namespace: Defines a scope that contains a set of identifiers.

Here’s an example of using some C++ keywords:

#include <iostream>
using namespace std;

int main() {
    int number = 10;  // 'int' is a keyword for integer data type
    if (number > 5) {  // 'if' is a keyword for conditional statement
        cout << "Number is greater than 5!" << endl;
    }
    return 0;  // 'return' is a keyword to exit the function
}

Complete List of C++ Keywords (for reference):

Here’s a complete list of keywords in C++:

alignas, alignof, and, and_eq, asm, auto, bitand, bitor, bool, break,
case, catch, char, char16_t, char32_t, class, compl, const, constexpr,
const_cast, continue, decltype, default, delete, do, double, dynamic_cast,
else, enum, explicit, export, extern, false, float, for, friend, goto,
if, inline, int, long, mutable, namespace, new, noexcept, not, not_eq,
nullptr, operator, or, or_eq, private, protected, public, reflexpr,
register, reinterpret_cast, requires, return, short, signed, sizeof,
static, static_assert, static_cast, struct, switch, template, this,
thread_local, throw, true, try, typedef, typeid, typename, union, unsigned,
using, virtual, void, volatile, wchar_t, while, xor, xor_eq

Note: You should avoid using these keywords as identifiers in your programs.


What Are C++ Identifiers?

An identifier is a name given to various program elements such as variables, functions, classes, arrays, etc. Identifiers are the building blocks of user-defined names in a C++ program.

Rules for Naming Identifiers

  1. Start with a letter or an underscore: Identifiers must start with a letter (A-Z, a-z) or an underscore (_).

    • Valid: age, _count, totalSum
    • Invalid: 123abc, 1_variable
  2. Followed by letters, digits, or underscores: After the first character, identifiers can contain letters, digits (0-9), or underscores.

    • Valid: total_sum, variable_1
    • Invalid: total-sum, first-name
  3. Cannot be a C++ keyword: Identifiers cannot be one of the reserved C++ keywords. For example, you cannot name a variable int or return.

  4. Case-sensitive: C++ is case-sensitive, meaning Variable, variable, and VARIABLE are three different identifiers.

    • Valid: TotalSum, totalSum, TOTALSUM
    • Invalid: totalSum and TotalSum if used in the same scope for different entities.
  5. No special characters or spaces: Identifiers cannot contain spaces or special characters (like @, #, etc.).

    • Valid: studentCount
    • Invalid: student@count, total sum
  6. Naming conventions: While C++ allows using any valid identifier, it’s important to follow naming conventions to make your code readable and consistent. Some common conventions include:

    • CamelCase: For variables, functions, and classes (e.g., totalSum, calculateArea).
    • snake_case: For variables and functions in some coding standards (e.g., total_sum, calculate_area).
    • PascalCase: For class names (e.g., StudentClass, ShapeArea).

Example of C++ Identifiers:

#include <iostream>
using namespace std;

int totalSum = 0; // Valid identifier
int main() {
    int totalSum = 5;  // Identifier with the same name as the global variable
    cout << "Total Sum: " << totalSum << endl; // Local variable used here
    return 0;
}

In this example:

  • totalSum is used as an identifier for both the global variable and the local variable.
  • The local variable totalSum hides the global one within the scope of main(), demonstrating how C++ handles scope and identifier resolution.

Best Practices for Naming Identifiers

  • Be Descriptive: Use meaningful and descriptive names for identifiers to make the code more readable.

    • Good: totalSum, studentAge, calculateArea
    • Bad: x, temp, a
  • Avoid Single-Character Identifiers: Use meaningful names instead of single characters, especially for variables representing more complex data.

    • Example: Use count instead of c, temperature instead of t.
  • Consistent Naming Conventions: Stick to a consistent naming convention throughout your code. For example, if you’re using camelCase for variables, continue using it for other identifiers.

  • Avoid Using Underscores for Single Words: While underscores are allowed, many developers prefer camelCase for variable names and function names, reserving snake_case for constant variables or when working in certain coding styles.

    • Example: studentAge (camelCase), MAX_SIZE (UPPERCASE with snake_case for constants).