Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

A Word about Variable Names and Keywords

This chapter has featured the variables ctemp, ftemp, and n. Exercise 1.3.4 suggested that you could replace “x” with “num,” as long as you do the substitution consistently throughout the program. So “num” is a valid name for a variable as well.

There is an endless variety of variable names I could have used instead. I could, for example, give some variables the names killerRobot or GovernorOfCalifornia.

What variable names are permitted, and what ones are not? You can use any name you want, as long as you follow these rules:

  • The first character should be a letter. It cannot be a number. The first character can be an underscore (_), but the C++ library uses that naming convention internally, so it’s best to avoid starting a name that way.
  • The rest of the name can be a letter, a number, or an underscore (_).
  • You must avoid words that already have a special, predefined meaning in C++, such as the keywords.

It isn’t necessary to sit down and memorize all the C++ keywords. You need to know only that if you try using a name that conflicts with one of the C++ keywords, the compiler will respond with an error message. In that case, try a different name.



Exercise 1.3.5. In the following list, which of the words are legal variable names in C++, and which are not? Review the rules just mentioned as needed.

  • x1
  • EvilDarkness
  • PennslyvaniaAve1600
  • 1600PennsylvaniaAve
  • Bobby_the_Robot
  • Bobby+the+Robot
  • whatThe???
  • amount
  • count2
  • count2five
  • 5count
  • main
  • main2
  • + Share This
  • 🔖 Save To Your Account