Short answer
C++ keywords are reserved words that have a fixed meaning in the language. Words such as int, class, return and if are part of the syntax, so you can’t use them as names for your own variables, functions or classes.
Keywords and names
int main() {
int count = 3; // count is a name you chose
// int class = 5; // Error: class is a keyword
int Class = 5; // Fine: C++ is case-sensitive, so Class is not a keyword
return 0;
}
The commented-out line won’t compile, and that is the kind of error you’d see. C++ is case-sensitive, so Class is an ordinary name even though class is a keyword.
Main groups of keywords
The full list is long, so here are the main groups with a few examples in each:
- Types:
bool,char,int,double,float,void - Literal values:
true,false,nullptr - Storage and qualifiers:
static,extern,const,constexpr,inline - Control flow:
if,else,switch,case,for,while,break,continue,return,goto - Classes and access:
class,struct,public,private,protected,virtual,friend - Templates and namespaces:
template,typename,namespace,using - Memory and type tools:
new,delete,sizeof,decltype - Error handling:
try,catch,throw
Some of these get their own treatment in access modifiers in c and the c const keyword. The goto jump is rarely needed in modern code, but for the mechanics see how to use goto in c.
Contextual keywords
A few words behave differently. final and override, both added in C++11, act as keywords only in specific positions, such as after a class name or in a virtual function declaration. Elsewhere they can still be used as ordinary names:
int final = 5; // Valid: final has no special meaning here
That compiles, but it is confusing, so it’s best avoided. For the details on how final works, read the c final keyword guide.
Alternative tokens
C++ also reserves words such as and, or and not, which are alternative spellings of the &&, || and ! operators. So this is an error:
int and = 1; // Error: and is an alternative spelling of &&
Names that aren’t keywords
Several familiar names are not keywords:
std,string,vectorandcoutare names from the standard library, not keywords. They live in thestdnamespace, which is why you often seestd::cout.NULLis a macro defined by standard library headers, not a keyword.mainhas a special role as the program’s entry point, but it is not a keyword.
Keywords change over time
The keyword list grows with each standard. C++11 added words such as nullptr, constexpr and decltype, and C++20 added words such as concept, requires and co_await.
If you’re unsure whether a word is reserved, check the list in the C++ standard that your compiler uses.
Avoiding keyword clashes
- Choose names that describe the data, such as
countorclass_name, rather than words likeclassornew. - When a compiler error points to an unexpected token, check whether one of your names is a keyword.