2.7. 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, return, using and many more.

C++ keywords are available publicly on cppreference. Many of the C++ language links from this textbook link to this site, for example:

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: source 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.

Caution

If you type a variable name and it turns the color of a keyword in your editor, then watch out! You might get some strange behavior from the compiler.

In addition to keywords, the facilities you include in your programs using #include add additional names that you want to avoid conflict with. The include files iostream, string, and vector are commonly included.

Note

Case matters! You can name a string variable String without an issue because C++ does not consider String to be the same as string. Also, a anything written in quotes, for example "string" is not considered a keyword or variable in C++, even if it is spelled the same.

Unlike variables and standard library objects like cout, you can’t put a variable or object in a namespace to avoid a name conflict with a language keyword. The language keywords are always “in scope”. More on scope and namespaces in the next chapter.

Fix the code below so that it runs without errors. Hint: you might need to change the names of some variables.


More to Explore

You have attempted of activities on this page