- What Is a Variable?
- Defining a Variable
- Assigning Values to Variables
- Using Type Definitions
- Constants
- Summary
- Q&A
- Workshop
- Activities
Defining a Variable
A variable is defined in C++ by stating its type, the variable name, and a colon to end the statement, as in this example:
int highScore;
More than one variable can be defined in the same statement as long as they share the same type. The names of the variables should be separated by commas, as in these examples:
unsigned int highScore, playerScore; long area, width, length;
The highScore and playerScore variables are both unsigned integers. The second statement creates three long integers: area, width, and length. Because these integers share the same type, they can be created in one statement.
A variable name can be any combination of uppercase and lowercase letters, numbers and underscore characters (_) without any spaces. Legal variable names include x, driver8, and playerScore. C++ is case sensitive, so the highScore variable differs from ones named highscore or HIGHSCORE.
Using descriptive variable names makes it easier to understand a program for the humans reading it. (The compiler doesn't care one way or the other.) Take a look at the following two code examples to see which one is easier to figure out.
Example 1.
main() { unsigned short x; unsigned short y; unsigned int z; z = x * y; } |
Example 2.
main () { unsigned short width; unsigned short length; unsigned short area; area = width * length; } |
Programmers differ in the conventions they adopt for variable names. Some prefer all lowercase letters for variable names with underscores separating words, such as high_score and player_score. Others prefer lowercase letters except for the first letter of new words, such as highScore and playerScore. (In a bit of programming lore, the latter convention has been dubbed CamelCase because the middle-of-word capitalization looks like a camel's hump.)
Programmers who learned in a UNIX environment tend to use the first convention, whereas those in the Microsoft world use CamelCase. The compiler does not care.
The code in this book uses CamelCase.
With well-chosen variable names and plenty of comments, your C++ code will be much easier to figure out when you come back to it months or years later.
Some words are reserved by C++ and may not be used as variable names because they are keywords used by the language. Reserved keywords include if, while, for, and main. Generally, any reasonable name for a variable is almost certainly not a keyword.
Variables may contain a keyword as part of a name but not the entire name, so variables mainFlag and forward are permitted but main and for are reserved.