int studentAge = 25;C++ Keywords and Identifiers: Naming Rules and Reserved Words
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:
intis a C++ keyword.studentAgeis an identifier.25is 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:
int age = 25;Here:
intis a keyword.
It tells the compiler that age is an integer object.
You cannot use int as a variable name:
int int = 10; // ErrorThe 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:
int age;
double salary;
void calculateTotal();
class Employee;Here:
ageis an identifier.salaryis an identifier.calculateTotalis an identifier.Employeeis an identifier.
Identifiers allow programmers to give meaningful names to different elements of a program.
Keywords vs Identifiers
The difference can be summarized simply:
| Feature | Keywords | Identifiers |
|---|---|---|
| Meaning | Defined by C++ | Defined by the programmer |
| Purpose | Language syntax | Naming program elements |
| Can you create your own? | No | Yes |
| Can be used as variable names? | Generally no | Yes |
| Examples | int, if, class, return | age, total, Student |
For example:
int age = 25;The compiler understands:
int → keyword
age → identifier
25 → literalC++ Identifier Naming Rules
C++ identifiers must follow specific lexical rules.
A basic identifier can contain:
Letters
Digits
Underscores
For example:
student
studentAge
student_age
age2
_totalHowever, there are important restrictions.
Rule 1: An Identifier Cannot Start With a Digit
This is invalid:
int 123age = 25;An identifier cannot begin with a number.
This is valid:
int age123 = 25;The digits can appear after the first character.
More examples:
int student1;
int value2;
int year2026;Rule 2: Letters, Digits, and Underscores Can Be Used
These are valid examples:
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:
age
Age
AGE
aGeFor example:
int age = 20;
int Age = 30;These are two different variables.
You can technically write:
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:
int student age = 25;C++ interprets student and age as separate tokens.
Use an underscore:
int student_age = 25;or camelCase:
int studentAge = 25;Rule 5: Special Symbols Are Generally Not Allowed
Characters such as:
@
#
$
%
!
&
*cannot normally be used as ordinary identifier characters.
For example:
int student@age = 25; // InvalidUse:
int studentAge = 25;instead.
Rule 6: Keywords Cannot Be Used as Ordinary Identifiers
This is invalid:
int class = 10;because class is a C++ keyword.
Other examples:
int return = 5; // Invalid
int if = 10; // Invalid
int while = 20; // InvalidUse descriptive alternatives:
int returnValue = 5;
int condition = 10;
int loopCount = 20;Valid C++ Identifiers
Here are some valid examples:
age
studentAge
student_age
total
totalPrice
price2
_number
_privateValue
calculateTotal
Employee
MAX_SIZEWhether 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:
123name
student age
student-age
student@name
class
returnWhy?
| Identifier | Reason |
|---|---|
123name | Starts with a digit |
student age | Contains a space |
student-age | - is not an identifier character |
student@name | @ is not a normal identifier character |
class | Reserved keyword |
return | Reserved keyword |
C++ Keyword List
C++ has a large collection of reserved keywords.
Common keywords include:
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_eqThe 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:
concept
requires
consteval
constinit
co_await
co_return
co_yieldThese 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.
| Keyword | Purpose |
|---|---|
int | Integer type |
double | Floating-point type |
char | Character type |
bool | Boolean type |
if | Conditional execution |
else | Alternative branch |
for | Loop |
while | Loop |
return | Return from a function |
class | Define a class |
struct | Define a structure |
public | Public class/struct access |
private | Private class access |
protected | Protected class access |
const | Defines non-modifiable objects/references depending on context |
static | Gives context-dependent static storage/linkage/class behavior |
namespace | Defines a namespace |
using | Introduces names or aliases |
new | Dynamic allocation |
delete | Releases dynamically allocated storage |
nullptr | Null pointer literal |
virtual | Supports virtual member functions |
template | Defines templates |
int as a Keyword
Consider:
int age = 30;The compiler recognizes int as a built-in type keyword.
You are declaring:
data type → int
identifier → age
value → 30if as a Keyword
Example:
if (age >= 18) {
std::cout << "Adult";
}Here:
ifis a keyword used for conditional execution.
You cannot write:
int if = 10;because if already has a defined meaning in C++.
class as a Keyword
The class keyword is used to define classes.
class Car {
public:
void start() {
std::cout << "Car started";
}
};Here:
classis a keyword, while:
Caris an identifier.
return as a Keyword
Example:
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:
int return = 10; // Errorconst as a Keyword
Example:
const int maxUsers = 100;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:
const int MAX_USERS = 100;but naming conventions vary between projects.
nullptr as a Keyword
Modern C++ provides:
nullptras the null pointer literal.
Example:
int* ptr = nullptr;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
studentName
totalPrice
calculateAveragesnake_case
student_name
total_price
calculate_averagePascalCase
StudentName
BankAccount
CalculateAverageUPPER_CASE
Often used for certain constants or macros:
MAX_SIZE
BUFFER_SIZEThe most important rule is consistency.
Common C++ Naming Convention Example
One possible style is:
class Student {
public:
std::string firstName;
int age;
void calculateAverage();
};Here:
Student→ class namefirstName→ variable/member nameage→ variable/member namecalculateAverage→ function name
A different project might use:
class StudentRecord {
public:
std::string first_name;
int age;
void calculate_average();
};Both styles can be valid.
Meaningful Identifiers
Prefer descriptive names.
Instead of:
int x;use:
int studentAge;Instead of:
double p;use:
double productPrice;Instead of:
int n;use:
int numberOfStudents;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:
for (int i = 0; i < 10; ++i) {
}Here i is widely understood as a loop index.
But this:
int x = 15000;
double y = 200.50;is harder to understand than:
int employeeId = 15000;
double monthlySalary = 200.50;Use names that communicate intent.
Avoid Misleading Identifiers
A variable name should accurately describe its value.
Avoid:
int age = 500;if the variable actually stores a product ID.
Prefer:
int productId = 500;Good naming is part of good program design.
Underscore Rules and Conventions
Underscores are allowed in identifiers:
student_name
_total
value_1However, 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:
__value
_ExampleAlso 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:
int studentAge = 20;
int studentage = 30;These are two different identifiers.
Similarly:
Student
student
STUDENTare 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:
int class = 10;does not create a variable called class.
The compiler sees:
int → type keyword
class → class declaration keywordand 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:
int classCount = 10;
int returnValue = 0;
int ifCondition = 1;These are valid identifiers.
The compiler recognizes:
classCount
returnValue
ifConditionas complete identifiers rather than the keywords class, return, and if.
Examples of Good and Bad Names
| Bad or confusing | Better |
|---|---|
x | studentAge |
p | productPrice |
n | numberOfItems |
data1 | customerAddress |
a | averageScore |
temp | temperatureCelsius |
The better name usually tells the reader what the value represents.
Identifiers in a C++ Program
Consider this program:
#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:
calculateSum
firstNumber
secondNumber
main
total
std
coutAnd several language keywords:
int
returnThis 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:
class
return
if
while
forare 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:
std::vector
std::string
std::cout
std::cin
std::sortThese are not all language keywords.
They are library names.
For example:
std::vector<int> numbers;Here:
std::vectoris a standard library class template, not a language keyword.
This distinction is important.
Keyword vs Standard Library Name
Compare:
int age;and:
std::vector<int> numbers;In the first example:
int → language keywordIn the second:
vector → standard library name
int → language keyword
numbers → programmer-defined identifierCan You Create a Variable Named vector?
Potentially, yes, depending on scope and namespace usage, because vector itself is not a C++ keyword.
For example:
int vector = 10;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:
studentName
totalPrice
employeeIdare 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:
const int maxStudents = 100;or:
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:
calculateTotal();
saveFile();
readData();
validateInput();
sendMessage();Less descriptive:
doIt();
process();
run();unless the context makes the purpose obvious.
Naming Classes
Class names commonly represent a concept or object.
Examples:
class Employee {
};
class BankAccount {
};
class ImageProcessor {
};A class name such as:
class Process {
};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:
bool isActive;
bool isLoggedIn;
bool hasPermission;
bool canEdit;For example:
bool isLoggedIn = true;
if (isLoggedIn) {
std::cout << "Welcome";
}This is usually easier to understand than:
bool x = true;
if (x) {
}Common Identifier Mistakes
Starting With a Number
int 2value = 10;Invalid.
Use:
int value2 = 10;Using Spaces
int first name = 10;Invalid.
Use:
int firstName = 10;Using a Hyphen
int student-age = 20;Invalid as an identifier.
Use:
int studentAge = 20;or:
int student_age = 20;Using a Keyword
int return = 10;Invalid.
Use:
int returnValue = 10;Using Inconsistent Capitalization
For example:
int studentAge = 20;
std::cout << StudentAge;This fails because:
studentAgeand:
StudentAgeare 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:
int studentAge;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:
int
class
if
return
whileCan a C++ keyword be used as a variable name?
No. A keyword cannot normally be used as an ordinary programmer-defined identifier.
For example:
int class = 10;is invalid.
Can a C++ identifier start with a number?
No.
This is invalid:
int 123value;This is valid:
int value123;Are C++ identifiers case-sensitive?
Yes.
These are different:
age
Age
AGECan C++ identifiers contain underscores?
Yes.
For example:
student_name
total_priceare valid identifiers.
Can C++ identifiers contain spaces?
No.
Use:
studentNameinstead of:
student nameCan a C++ identifier contain a keyword?
A keyword can appear as part of a longer identifier.
For example:
int returnValue;is valid.
But:
int return;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:
std::string name;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:
┌─────────────────────────┬─────────────────────────┐
│ 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:
VALID INVALID
studentAge 123student
student_age student age
value2 student-age
totalPrice classAdd a small footer:
“Keywords belong to the language. Identifiers belong to your program.”
Runnable Code Example: C++ Keywords and Identifiers
C++20 / C++23#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 PrepQ: Why are identifiers starting with double underscore reserved?
Q: What is the difference between constexpr and consteval?
Key Takeaways, Modern Best Practices & Idioms
C++ Best Practices & Production Rules
2. Avoid leading underscores in variable names to prevent compiler namespace clashes.
3. Choose descriptive names that describe the domain intent rather than abbreviations.