Best Practices

Reserved Keywords in C++

DIFFICULTY: Beginner READ TIME: 5 mins

Hey! Welcome back. Today, we’re finishing up our journey with a quick, handy reference sheet: Reserved Keywords in C++.

In programming, a keyword is a special word that has a pre-defined meaning in the language. You can think of them like “registered trademarks” of the C++ compiler. Because the compiler relies on these words to parse your loops, classes, and variable declarations, you are not allowed to use them as names for your variables, functions, or classes. They are the ultimate VIPs of the C++ world!


Naming Rules: Validating Identifiers

An identifier is just a developer-made name for a variable, function, class, or namespace. To write valid identifiers that compile, they must pass this validation check:

graph TD
    start[Proposed Identifier Name] --> check_first{Starts with a letter <br/> or underscore _ ?}
    check_first -->|No| invalid[INVALID: Compiler error]
    check_first -->|Yes| check_chars{Contains only letters, <br/> digits, or underscores?}
    
    check_chars -->|No| invalid
    check_chars -->|Yes| check_keyword{Is it a reserved <br/> C++ keyword?}
    
    check_keyword -->|Yes| invalid
    check_keyword -->|No| valid[VALID IDENTIFIER]

Invalid vs. Valid Identifier Implementations

If you try to declare a variable using a keyword, the compiler will fail immediately:

Example (Fails Compilation):

#include <iostream>

int main() {
    // int double = 100; // ERROR! 'double' is a reserved keyword for a data type.
    // float class = 3.14; // ERROR! 'class' is a reserved keyword for OOP blueprints.
    return 0;
}

Example (Valid Naming):

#include <iostream>

int main() {
    double doubleVal = 100.0; // Valid (camelCase descriptor)
    float classSize = 3.14f;  // Valid
    return 0;
}

Categorized Reference of C++ Keywords

To make this chapter actually useful, we’ve broken down all standard C++ keywords into logical categories. Instead of looking at a giant alphabetical list, you can check what each keyword is for:

1. Basic Data Types

These keywords define primitive variable types:

KeywordDescription
boolBoolean type (holds true or false).
char / wchar_tCharacter types (single characters, wide characters).
char8_t / char16_t / char32_tUnicode character representations (introduced in C++20/C++11).
int / short / longSigned integer types of varying sizes.
float / doubleSingle and double precision floating-point numbers.
voidRepresents the absence of type (commonly return type for functions that return nothing).
signed / unsignedSign specifiers for integer types.

2. Control Flow & Loops

These keywords direct the execution path of your program:

KeywordDescription
if / elseConditional branching statements.
switch / case / defaultMulti-way branching selection statements.
for / while / doLoop iteration constructs.
breakExits the innermost loop or switch block immediately.
continueSkips the remaining lines in a loop and moves to the next iteration.
gotoJumps to a defined label (strongly discouraged in modern code!).
returnExits a function and optionally returns a value.

3. Classes & Object-Oriented Programming

These keywords build class structures, encapsulation, and inheritance:

KeywordDescription
class / structDeclares classes or structures. (Only difference is default public/private access).
public / private / protectedAccess specifiers defining visibility boundaries.
thisA pointer representing the current object instance inside member functions.
virtualDeclares virtual methods for runtime overriding.
friendDeclares friend classes or functions, granting access to private fields.
explicitPrevents the compiler from performing implicit type conversions on constructors.
operatorUsed to overload standard operators.
enumDeclares enumerations (custom groupings of constants).
unionStruct-like container where all members share the same memory location.

4. Memory & Modifiers

These keywords modify scope, lifetime, or memory access:

KeywordDescription
new / deleteAllocates and deallocates dynamic heap memory.
autoAutomatic type deduction.
const / volatileRead-only variables / variables that can change outside program control.
constexpr / consteval / constinitConstants evaluated at compile-time (C++11, C++20).
staticPreserves variable lifetime across calls or restricts visibility to file scope.
externTells the compiler a variable/function is defined in another source file.
mutableAllows a member variable to be modified even inside a const function.
thread_localDeclares variables unique to each running execution thread.

5. Advanced & Metaprogramming

These keywords handle templates, casting, exceptions, and concepts:

KeywordDescription
template / typenameDeclares templates and generic type parameters.
try / catch / throwException handling mechanisms.
noexceptDeclares that a function will not throw exceptions.
concept / requiresConstraints on template parameters (introduced in C++20).
static_cast / dynamic_castSafe compile-time type casting / checked inheritance casting.
const_cast / reinterpret_castCasts away const status / raw binary memory casts.
sizeof / alignof / alignasQueries object size / queries alignment / specifies custom alignment.
decltypeQueries the type of an expression at compile-time.
static_assertPerforms compile-time assertion checks.
namespace / usingDeclares logical scopes / imports items from scopes.

Identifiers with Special Meaning (Contextual Keywords)

In addition to fully reserved keywords, C++ has contextual keywords. These words are only treated as reserved inside specific code declarations (like inheritance classes or template imports). You can technically use them as variable names, but you should avoid it to prevent confusion:

  • override: Declares that a member function overrides a virtual function from a base class.
  • final: Prevents a class from being inherited or a virtual function from being overridden.
  • import / module: Used for modular imports in C++20 compilation units.

Example:

#include <iostream>

int main() {
    int override = 10; // VALID compilation (override is only contextual in classes)
    int final = 20;    // VALID compilation
    
    std::cout << "Override: " << override << ", Final: " << final << std::endl;
    return 0;
}

Output:

Override: 10, Final: 20

Conclusion

Understanding reserved keywords is like knowing the road signs in a city. By knowing which terms are reserved, you write cleaner code that compiler parsers understand immediately, preventing naming collisions and saving valuable debugging time!

quiz Test Your Understanding

Which of the following is NOT a reserved keyword in C++?