Keywords in C++
Keywords are the reserved words in C++ which have a special meaning for the compiler. These words cannot be used as identifiers (like variable names, function names, or class names) because they are already defined by the C++ language for specific purposes.
Keywords are written in lowercase letters (mostly) and help in building the structure of a program. Using them incorrectly will result in a compilation error.
Rules for Keywords
Important Rules:
- Keywords cannot be used as variable names, function names, or identifiers.
- They are case-sensitive in C++.
- Some keywords are specific to newer C++ versions (like
char8_t,concept). - Using a keyword as an identifier will cause a compilation error.
Common C++ Keywords
| Keywords | Keywords | Keywords | Keywords | Keywords |
|---|---|---|---|---|
int |
float |
char |
return |
void |
if |
else |
for |
while |
break |
class |
public |
private |
new |
delete |
Total Number of Keywords
As per the C++20 standard, there are 95 keywords defined in the language.
Examples of Keywords:
int main() {
int age = 18; // 'int' is a keyword
if (age >= 18) { // 'if' is a keyword
return 0; // 'return' is a keyword
}
}
Explanation:
- int → used to declare integer type variable.
- if → used for conditional execution.
- return → used to return value from function.
Real-Life Analogy:
Just like traffic signs on the road have fixed meanings (you cannot change their meaning), keywords in C++ also have fixed meanings and cannot be used for anything else.
Example: Valid vs Invalid Usage
// ✅ Valid
int number = 10;
bool isTrue = true;
// ❌ Invalid
int return = 5; // give error 'return' is a keyword
Output:
Error: expected unqualified-id before ‘return’
Explanation:
- In the second case,
returnis a keyword, so it cannot be used as a variable name. - The first example works fine because identifiers do not match any reserved keywords.
Summary:
- Keywords are reserved words predefined in C++.
- They cannot be used as identifiers (variable or function names).
- They form the syntax and structure of the program.
- Examples: int, if, return, class, while.