Topic 8 of 91 2. C++ Fundamentals Interactive Tutorial

C++ Keywords and Identifiers: Naming Rules and Reserved Words

12 mins read Last updated: 26 Sep 2026 17,900 views

Direct Answer & Core Concept

When writing C++ programs, you constantly create names for variables, functions, classes, objects, constants, and other parts of your code. At the same time, C++ has a collection of special words that already have a predefined meaning in the language.

These two concepts are called identifiers and keywords.

For example:

Here:

  • int is a C++ keyword.

  • studentAge is an identifier.

  • 25 is an integer literal.

Understanding the difference between keywords and identifiers is essential because C++ has strict rules about which names you can create and which words are reserved by the language.

Detailed Explanation & Mechanics

What Are C++ Keywords?

A keyword is a word that has a predefined meaning in the C++ language.

Keywords are part of the C++ syntax and cannot normally be used as identifiers for your own variables, functions, classes, or other declarations.

For example:

Here:

is a keyword.

It tells the compiler that age is an integer object.

You cannot use int as a variable name:

The compiler interprets int as the language keyword rather than as a user-defined name.


What Are Identifiers in C++?

An identifier is a name given to a program element.

Examples include:

main.cpp
Run Online
int age;
double salary;

void calculateTotal();

class Employee;

Here:

  • age is an identifier.

  • salary is an identifier.

  • calculateTotal is an identifier.

  • Employee is an identifier.

Identifiers allow programmers to give meaningful names to different elements of a program.


Keywords vs Identifiers

The difference can be summarized simply:

FeatureKeywordsIdentifiers
MeaningDefined by C++Defined by the programmer
PurposeLanguage syntaxNaming program elements
Can you create your own?NoYes
Can be used as variable names?Generally noYes
Examplesint, if, class, returnage, total, Student

For example:

The compiler understands:

main.cpp
Run Online
int → keyword
age → identifier
25 → literal

C++ Identifier Naming Rules

C++ identifiers must follow specific lexical rules.

A basic identifier can contain:

  • Letters

  • Digits

  • Underscores

For example:

main.cpp
Run Online
student
studentAge
student_age
age2
_total

However, there are important restrictions.


Rule 1: An Identifier Cannot Start With a Digit

This is invalid:

An identifier cannot begin with a number.

This is valid:

The digits can appear after the first character.

More examples:

main.cpp
Run Online
int student1;
int value2;
int year2026;

Rule 2: Letters, Digits, and Underscores Can Be Used

These are valid examples:

main.cpp
Run Online
int age;
int student_age;
int studentAge;
int age25;
int value_2;

The exact identifier character rules are based on the C++ language's identifier syntax, including support for certain Unicode characters in appropriate source environments, but simple ASCII letters, digits, and underscores are the safest and most portable naming choice.


Rule 3: Identifiers Are Case-Sensitive

C++ distinguishes between uppercase and lowercase letters.

These are different identifiers:

For example:

main.cpp
Run Online
int age = 20;
int Age = 30;

These are two different variables.

You can technically write:

main.cpp
Run Online
int age = 20;
int Age = 30;

but using names that differ only by capitalization can make code confusing.


Rule 4: Spaces Are Not Allowed

This is invalid:

C++ interprets student and age as separate tokens.

Use an underscore:

or camelCase:


Rule 5: Special Symbols Are Generally Not Allowed

Characters such as:

cannot normally be used as ordinary identifier characters.

For example:

main.cpp
Run Online
int student@age = 25; // Invalid

Use:

instead.


Rule 6: Keywords Cannot Be Used as Ordinary Identifiers

This is invalid:

because class is a C++ keyword.

Other examples:

main.cpp
Run Online
int return = 5; // Invalid
int if = 10;    // Invalid
int while = 20; // Invalid

Use descriptive alternatives:

main.cpp
Run Online
int returnValue = 5;
int condition = 10;
int loopCount = 20;

Valid C++ Identifiers

Here are some valid examples:

main.cpp
Run Online
age
studentAge
student_age
total
totalPrice
price2
_number
_privateValue
calculateTotal
Employee
MAX_SIZE

Whether a particular naming style is recommended is a separate question from whether the identifier is syntactically valid.


Invalid C++ Identifiers

Examples of invalid identifiers include:

main.cpp
Run Online
123name
student age
student-age
student@name
class
return

Why?

IdentifierReason
123nameStarts with a digit
student ageContains a space
student-age- is not an identifier character
student@name@ is not a normal identifier character
classReserved keyword
returnReserved keyword

C++ Keyword List

C++ has a large collection of reserved keywords.

Common keywords include:

main.cpp
Run Online
alignas
alignof
and
and_eq
asm
auto
bitand
bitor
bool
break
case
catch
char
char8_t
char16_t
char32_t
class
compl
concept
const
consteval
constexpr
constinit
const_cast
continue
co_await
co_return
co_yield
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

The exact keyword set depends on the C++ standard version, and some entries have specialized or historical status.

For example, newer C++ standards introduced keywords such as:

main.cpp
Run Online
concept
requires
consteval
constinit
co_await
co_return
co_yield

These are associated with modern language features.


Common C++ Keywords and Their Uses

You do not need to memorize the entire keyword list at once.

Start with the keywords you encounter frequently.

KeywordPurpose
intInteger type
doubleFloating-point type
charCharacter type
boolBoolean type
ifConditional execution
elseAlternative branch
forLoop
whileLoop
returnReturn from a function
classDefine a class
structDefine a structure
publicPublic class/struct access
privatePrivate class access
protectedProtected class access
constDefines non-modifiable objects/references depending on context
staticGives context-dependent static storage/linkage/class behavior
namespaceDefines a namespace
usingIntroduces names or aliases
newDynamic allocation
deleteReleases dynamically allocated storage
nullptrNull pointer literal
virtualSupports virtual member functions
templateDefines templates

int as a Keyword

Consider:

The compiler recognizes int as a built-in type keyword.

You are declaring:

main.cpp
Run Online
data type → int
identifier → age
value → 30

if as a Keyword

Example:

main.cpp
Run Online
if (age >= 18) {
    std::cout << "Adult";
}

Here:

is a keyword used for conditional execution.

You cannot write:

because if already has a defined meaning in C++.


class as a Keyword

The class keyword is used to define classes.

main.cpp
Run Online
class Car {
public:
    void start() {
        std::cout << "Car started";
    }
};

Here:

is a keyword, while:

is an identifier.


return as a Keyword

Example:

main.cpp
Run Online
int add(int a, int b) {
    return a + b;
}

The return keyword tells the function to return a value.

It cannot be used as an ordinary identifier:


const as a Keyword

Example:

const is a keyword that expresses a constant or non-modifiable object in this context.

maxUsers is the identifier.

A common naming style for constants is:

main.cpp
Run Online
const int MAX_USERS = 100;

but naming conventions vary between projects.


nullptr as a Keyword

Modern C++ provides:

as the null pointer literal.

Example:

This is preferable to using the integer literal 0 or the old NULL macro for modern C++ pointer code.


Contextual Keywords

C++ also has words that can behave specially depending on context.

Some words have special meanings in particular language constructs without always behaving exactly like traditional reserved keywords.

This distinction becomes important when studying advanced C++ syntax.

For beginner programming, the practical rule is simple:

Do not use standard C++ language words or special language tokens as your own identifiers unless you fully understand the relevant language rules.


Identifier Naming Conventions

C++ does not force you to use one particular naming style.

However, projects usually establish a naming convention.

Common styles include:

camelCase

main.cpp
Run Online
studentName
totalPrice
calculateAverage

snake_case

main.cpp
Run Online
student_name
total_price
calculate_average

PascalCase

main.cpp
Run Online
StudentName
BankAccount
CalculateAverage

UPPER_CASE

Often used for certain constants or macros:

The most important rule is consistency.


Common C++ Naming Convention Example

One possible style is:

main.cpp
Run Online
class Student {
public:
    std::string firstName;
    int age;

    void calculateAverage();
};

Here:

  • Student → class name

  • firstName → variable/member name

  • age → variable/member name

  • calculateAverage → function name

A different project might use:

main.cpp
Run Online
class StudentRecord {
public:
    std::string first_name;
    int age;

    void calculate_average();
};

Both styles can be valid.


Meaningful Identifiers

Prefer descriptive names.

Instead of:

use:

Instead of:

use:

Instead of:

use:

Meaningful names reduce the need for comments and make code easier to understand.


Avoid Extremely Short Names

Short names can be appropriate for small scopes.

For example:

main.cpp
Run Online
for (int i = 0; i < 10; ++i) {
}

Here i is widely understood as a loop index.

But this:

main.cpp
Run Online
int x = 15000;
double y = 200.50;

is harder to understand than:

main.cpp
Run Online
int employeeId = 15000;
double monthlySalary = 200.50;

Use names that communicate intent.


Avoid Misleading Identifiers

A variable name should accurately describe its value.

Avoid:

if the variable actually stores a product ID.

Prefer:

Good naming is part of good program design.


Underscore Rules and Conventions

Underscores are allowed in identifiers:

main.cpp
Run Online
student_name
_total
value_1

However, some underscore patterns are reserved for the implementation.

In particular, identifiers beginning with an underscore followed by another underscore, or identifiers beginning with an underscore followed by a capital letter, are reserved in many contexts.

For example, avoid creating names such as:

Also be careful with underscore-prefixed names at global scope because many such names are reserved to the implementation.

A safe practical rule for beginners is:

Avoid leading underscores for your own application-level identifiers.


C++ Identifiers Are Case-Sensitive

Consider:

main.cpp
Run Online
int studentAge = 20;
int studentage = 30;

These are two different identifiers.

Similarly:

are different names.

Although the compiler allows them, using names that differ only by capitalization can cause mistakes.


Keywords Cannot Be Renamed

You cannot redefine the meaning of a C++ keyword.

For example:

does not create a variable called class.

The compiler sees:

main.cpp
Run Online
int → type keyword
class → class declaration keyword

and the syntax becomes invalid.


Can a Keyword Be Used Inside a Longer Identifier?

Yes.

A keyword cannot normally be used as the complete identifier, but it can form part of a longer identifier.

For example:

main.cpp
Run Online
int classCount = 10;
int returnValue = 0;
int ifCondition = 1;

These are valid identifiers.

The compiler recognizes:

main.cpp
Run Online
classCount
returnValue
ifCondition

as complete identifiers rather than the keywords class, return, and if.


Examples of Good and Bad Names

Bad or confusingBetter
xstudentAge
pproductPrice
nnumberOfItems
data1customerAddress
aaverageScore
temptemperatureCelsius

The better name usually tells the reader what the value represents.


Identifiers in a C++ Program

Consider this program:

main.cpp
Run Online
#include <iostream>

int calculateSum(int firstNumber, int secondNumber) {
    return firstNumber + secondNumber;
}

int main() {
    int firstNumber = 10;
    int secondNumber = 20;

    int total = calculateSum(firstNumber, secondNumber);

    std::cout << total;

    return 0;
}

There are several identifiers here:

main.cpp
Run Online
calculateSum
firstNumber
secondNumber
main
total
std
cout

And several language keywords:

This illustrates how keywords and identifiers work together to form a C++ program.


Reserved Words vs Identifiers

The term reserved word is often used when discussing words that cannot be used as ordinary programmer-defined names.

For example:

are reserved for C++ language functionality.

Your identifiers must not conflict with these reserved names.


C++ Standard Library Names

Not every name you should avoid is technically a C++ keyword.

The standard library also provides many names, such as:

main.cpp
Run Online
std::vector
std::string
std::cout
std::cin
std::sort

These are not all language keywords.

They are library names.

For example:

Here:

is a standard library class template, not a language keyword.

This distinction is important.


Keyword vs Standard Library Name

Compare:

and:

In the first example:

In the second:

main.cpp
Run Online
vector → standard library name
int → language keyword
numbers → programmer-defined identifier

Can You Create a Variable Named vector?

Potentially, yes, depending on scope and namespace usage, because vector itself is not a C++ keyword.

For example:

is syntactically possible.

However, it is a poor naming choice if the code also uses std::vector, because it can create confusion.

Prefer meaningful names that do not unnecessarily shadow important library names.


Unicode Identifiers

Modern C++ supports more than simple ASCII identifiers in appropriate source encodings.

For example, C++ allows certain Unicode characters in identifiers.

However, for professional and portable code, simple English ASCII-based identifiers such as:

main.cpp
Run Online
studentName
totalPrice
employeeId

are generally easier for teams to read, search, maintain, and use across development tools.


Naming Constants

Constants can be named using different project conventions.

For example:

main.cpp
Run Online
const int maxStudents = 100;

or:

main.cpp
Run Online
const int MAX_STUDENTS = 100;

Both are valid C++.

Modern C++ projects often use naming conventions based on their codebase rather than one universal rule.


Naming Functions

Use a verb or verb phrase when the function performs an action.

Good examples:

main.cpp
Run Online
calculateTotal();
saveFile();
readData();
validateInput();
sendMessage();

Less descriptive:

unless the context makes the purpose obvious.


Naming Classes

Class names commonly represent a concept or object.

Examples:

main.cpp
Run Online
class Employee {
};

class BankAccount {
};

class ImageProcessor {
};

A class name such as:

may be valid but can be too generic in a large project.


Naming Boolean Variables

Boolean variables often read naturally when given names such as:

main.cpp
Run Online
bool isActive;
bool isLoggedIn;
bool hasPermission;
bool canEdit;

For example:

main.cpp
Run Online
bool isLoggedIn = true;

if (isLoggedIn) {
    std::cout << "Welcome";
}

This is usually easier to understand than:


Common Identifier Mistakes

Starting With a Number

Invalid.

Use:


Using Spaces

Invalid.

Use:


Using a Hyphen

Invalid as an identifier.

Use:

or:


Using a Keyword

Invalid.

Use:


Using Inconsistent Capitalization

For example:

main.cpp
Run Online
int studentAge = 20;

std::cout << StudentAge;

This fails because:

and:

are different identifiers.


Quick Identifier Checklist

Before creating an identifier, check:

  • Does it start with a valid identifier character?

  • Does it avoid spaces?

  • Does it avoid invalid symbols?

  • Does it avoid C++ keywords?

  • Is it descriptive?

  • Is the capitalization consistent?

  • Does it follow the project's naming convention?

  • Does it avoid reserved implementation patterns?

  • Could it be confused with an important library name?


Frequently Asked Questions

What is an identifier in C++?

An identifier is a name used to identify a program element such as a variable, function, class, object, or namespace.

Example:

studentAge is the identifier.

What is a keyword in C++?

A keyword is a word reserved by the C++ language for a specific purpose.

Examples include:

Can a C++ keyword be used as a variable name?

No. A keyword cannot normally be used as an ordinary programmer-defined identifier.

For example:

is invalid.

Can a C++ identifier start with a number?

No.

This is invalid:

This is valid:

Are C++ identifiers case-sensitive?

Yes.

These are different:

Can C++ identifiers contain underscores?

Yes.

For example:

are valid identifiers.

Can C++ identifiers contain spaces?

No.

Use:

instead of:

Can a C++ identifier contain a keyword?

A keyword can appear as part of a longer identifier.

For example:

is valid.

But:

is invalid.

How many C++ keywords are there?

The keyword set depends on the C++ language standard and includes core language keywords plus newer keywords introduced by later standards. The safest approach is to use a current standard reference when you need the exact complete list for a particular C++ version.

What is the difference between a keyword and a reserved word?

In beginner discussions, the terms are often used interchangeably for words reserved by the language. More precisely, C++ has language keywords as well as other names and identifier patterns reserved for the implementation.

Is std::string a C++ keyword?

No. std::string is a standard library type. The keyword in a declaration such as:

is not string; string comes from the standard library.

Is main a C++ keyword?

No. main has a special role as the program entry point, but it is not classified as an ordinary C++ keyword.

Can I use vector as a variable name?

vector is not a C++ language keyword, so it can be used in some contexts. However, using names that conflict with familiar standard-library names can make code confusing and should generally be avoided when unnecessary.

Suggested Graphic Design

Create a clean programming infographic titled:

“C++ Keywords vs Identifiers”

Use a two-column design:

Architecture Diagram
┌─────────────────────────┬─────────────────────────┐
│      C++ KEYWORDS       │      IDENTIFIERS        │
├─────────────────────────┼─────────────────────────┤
│ int                     │ studentAge             │
│ class                   │ totalPrice             │
│ if                      │ calculateTotal         │
│ return                  │ Employee               │
│ while                   │ numberOfStudents       │
├─────────────────────────┼─────────────────────────┤
│ Defined by C++          │ Created by programmer  │
│ Reserved meaning        │ Used for naming        │
│ Cannot normally be      │ Must follow identifier │
│ used as custom names    │ naming rules           │
└─────────────────────────┴─────────────────────────┘

Add a second visual underneath:

main.cpp
Run Online
VALID                    INVALID

studentAge               123student
student_age              student age
value2                   student-age
totalPrice               class

Add a small footer:

“Keywords belong to the language. Identifiers belong to your program.”

Runnable Code Example: C++ Keywords and Identifiers

C++20 / C++23
main.cpp
Run Online
#include <iostream>
#include <string>

class NetworkClient {
private:
    std::string serverHost;
    int connectionPort;

public:
    NetworkClient(const std::string& host, int port)
        : serverHost(host), connectionPort(port) {}

    void connect() const {
        std::cout << "Connecting to " << serverHost << ":" << connectionPort << "
";
    }
};

int main() {
    NetworkClient client("api.operatetools.com", 443);
    client.connect();
    return 0;
}

Common C++ Technical Interview Questions & Answers

Interview Prep
Q

Q: Why are identifiers starting with double underscore reserved?

A: The ISO C++ standard reserves double underscores and leading underscore plus uppercase letter for compiler vendors and library implementers to prevent collisions with user code.
Q

Q: What is the difference between constexpr and consteval?

A: `constexpr` functions can be evaluated at compile time if arguments are constant, but can also run at runtime. `consteval` functions (immediate functions) MUST evaluate at compile time or fail compilation.

Key Takeaways, Modern Best Practices & Idioms

C++ Best Practices & Production Rules

1. Use camelCase for variables/functions and PascalCase for types and classes.
2. Avoid leading underscores in variable names to prevent compiler namespace clashes.
3. Choose descriptive names that describe the domain intent rather than abbreviations.