< Previous | Contents | Next >
To declare a variable, you must provide a name, known as an identifier. There are only a few rules you have to follow to create a legal identifier.
n An identifier can contain only numbers, letters, and underscores.
n An identifier can’t start with a number.
n An identifier can’t be a Cþþ keyword.
A keyword is a special word that Cþþ reserves for its own use. There aren’t many, but to see a full list, check out Appendix C.
In addition to the rules for creating legal variable names, following are some guidelines for creating good variable names.
n Choose descriptive names. Variable names should be clear to another programmer. For example, use score instead of s. (One exception to this rule involves variables used for a brief period. In that case, single-letter variable names, such as x, are fine.)
n Be consistent. There are different schools of thought about how to write multiword variable names. Is it high_score or highScore? In this book, I use the second style, where the initial letter of the second word (and any other words) is capitalized, known as camel case. But as long as you’re consistent, it’s not important which method you use.
n Follow the traditions of the language. Some naming conventions are just traditions. For example, in most languages (Cþþ included) variable names start with a lowercase letter. Another tradition is to avoid using an underscore as the first character of your variable names. Names that begin with an underscore can have special meaning.
n Keep the length in check. Even though playerTwoBonusForRoundOne is descriptive, it can make code hard to read. Plus, long names increase the risk of a typo. As a guideline, try to limit your variable names to fewer
Declaring and Initializing Variables 21
than 15 characters. Ultimately, though, your compiler sets an actual upper limit.
Tric k
Self-documenting code is written in such a way that it’s easy to understand what is happening in the program independent of any comments. Choosing good variable names is an excellent step toward this kind of code.