2.6. Keywords¶
A few sections ago, I said that you can make up any name you want for
your variables, but that’s not quite true. There are certain words that
are reserved in C++ because they are used by the compiler to parse the
structure of your program, and if you use them as variable names, it
will get confused. These words, called keywords, include int
, char
,
void
, endl
and many more.
A list of C++ keywords is availiable publically on cppreference
. You can
take a look for yourself by pasting the following link into your browser.
https://en.cppreference.com/w/cpp/keyword
Rather than memorize the list, I would suggest that you take advantage of a feature provided in many development environments: code highlighting. As you type, different parts of your program should appear in different colors. For example, keywords might be blue, strings red, and other code black.
Warning
If you type a variable name and it turns blue, watch out! You might get some strange behavior from the compiler.
Note
Case matters! You can name a string
variable String
without an issue
because C++ does not consider String
to be the same as keyword string
.
Also, a anything written in quotes, for example "string"
is not considered
a keyword in C++, even if it is spelt the same.
- integer
- integer is not a keyword, but int is.
- cout
- cout cannot be used as a variable name!
- variable
- variable is fair game to use to name a variable.
- string
- string cannot be used as a variable name.
- char
- char is a keyword and cannot be used as a variable name.
Q-2: Multiple Response: Which of the following are keywords or will otherwise generate some error from the compiler if used as a variable name?
int main() { double x = 1.0; int y = x + 5; bool Bool; string s = "void"; if (y > x) { Bool = true; } cout << Bool << endl; }
Fix the code below so that it runs without errors. Hint: you might need to change the names of some variables.