Variables
Variables have characteristics. When you decide your program needs another variable, you simply declare a new variable and C++ ensures that you get it. In C++, variable declarations can be placed anywhere in the program, as long as they are not referenced until after they are declared. To declare a variable, you must understand the possible characteristics, which follow.
-
Each variable has a name.
-
Each variable has a type.
-
Each variable holds a value that you put there, by assigning it to
that variable.
The following sections explain each of these characteristics in detail.
Naming Variable s
Because you can have many variables in a single program, you must assign names to them to keep track of them. Variable names are unique, just as house addresses are unique. If two variables have the same name, C++ would not know to which you referred when you request one of them.
Variable names can be as short as a single letter or as long as 32 characters. Their names must begin with a letter of the alphabet but, after the first letter, they can contain letters, numbers, and under- score ( _ ) characters.
EXAMPLE
Do not give variables the same name as a command or built-in function.
The following list of variable names are all valid:
sal ar y aug91_sal es i i ndex_age amount
It is traditional to use lowercase letters for C++ variable names. You do not have to follow this tradition, but you should know that uppercase letters in variable names are different from lowercase letters. For example, each of the following four variables is viewed differently by your C++ compiler.
sal es Sal es SALES sALES
Be very careful with the Shift key when you type a variable name. Do not inadvertently change the case of a variable name throughout a program. If you do, C++ interprets them as distinct and separate variables.
Variables cannot have the same name as a C++ command or function. Appendix E, “Keyword and Function Reference,” shows a list of all C++ command and function names.
The following are invalid variable names:
81_sal es Aug91+Sal es MY AGE pr i ntf
Chapter 4 ♦ Variables and Literals
Variable Type s
Variables can hold different types of data. Table 4.1 lists the different types of C++ variables. For instance, if a variable holds an integer, C++ assumes no decimal point or fractional part (the part to the right of the decimal point) exists for the variable’s value. A large number of types are possible in C++. For now, the most important types you should concentrate on are char , i nt , and f l oat . You can append the prefix l ong to make some of them hold larger values than they would otherwise hold. Using the unsi gned prefix enables them to hold only positive numbers.
Table 4.1. Some C++ variable types.
Declaration Name Type
char Character
unsi gned char Unsigned character
si gned char Signed character (same as char )
i nt Integer
unsi gned i nt Unsigned integer
si gned i nt Signed integer (same as i nt )
shor t i nt Short integer
unsi gned shor t i nt Unsigned short integer
si gned shor t i nt Signed short integer (same as shor t i nt )
l ong Long integer
l ong i nt Long integer (same as l ong )
si gned l ong i nt Signed long integer (same as l ong i nt )
unsi gned l ong i nt Unsigned long integer
f l oat Floating-point
doubl e Double floating-point
l ong doubl e Long double floating-point
EXAMPLE
The next section more fully describes each of these types. For now, you have to concentrate on the importance of declaring them before using them.
Declaring Variable s
There are two places you can declare a variable:
-
Before the code that uses the variable
-
Before a function name (such as before mai n() in the program)
The first of these is the most common, and is used throughout much of this book. (If you declare a variable before a function name, it is called a global variable. Chapter 17, “Variable Scope,” addresses the pros and cons of global variables.) To declare a variable, you must state its type, followed by its name. In the previous chapter, you saw a program that declared four variables in the following way.
Start of the mai n() function.
Declare the variables i and j as integers. Declare the variable c as a character.
Declare the variable x as a floating-point variable.
mai n( )
{
Declare all variables in a C++ program before you use them.
i nt i , j ; / / These t hr ee li nes decl ar e f our var i abl es. char c;
f l oat x;
/ / The r est of pr ogr am f oll ows.
This declares two integer variables named i and j . You have no idea what is inside those variables, however. You generally cannot assume a variable holds zero—or any other number—until you assign it a value. The first line basically tells C++ the following:
“I am going to use two integer variables somewhere in this program. Be expecting them. I want them named i and j . When I put a value into i or j , I ensure that the value is an integer.”
Chapter 4 ♦ Variables and Literals
Without such a declaration, you could not assign i or j a value later. All variables must be declared before you use them. This does not necessarily hold true in other programming languages, such as BASIC, but it does for C++. You could declare each of these two variables on its own line, as in the following code:
mai n( )
{
i nt i ;
i nt j ;
/ / The r est of pr ogr am f oll ows.
You do not gain any readability by doing this, however. Most C++ programmers prefer to declare variables of the same type on the same line.
The second line in this example declares a character variable called c. Only single characters should be placed there. Next, a floating-point variable called x is declared.
Examples
- Suppose
you had to keep track of a person’s first, middle, and last initials. Because an initial is obviously a character, it would be prudent to declare three character variables to hold the three initials. In C++, you could do that with the following statement:
mai n( )
{
char f i r st , mi ddl e, l ast;
/ / The r est of pr ogr am f oll ows.
This statement could go after the opening brace of mai n() . It informs the rest of the program that you require these three character variables.
- You
could declare these three variables also on three sepa- rate lines, although it does not necessarily improve readabil- ity to do so. This could be accomplished with:
EXAMPLE
mai n( )
{
char f i r st; char mi ddl e; char l ast;
/ / The r est of pr ogr am f oll ows.
- Suppose you want to keep track of a person’s age and weight. If you
want to store these values as whole numbers, they would probably go in integer variables. The following statement would declare those variables:
mai n( )
{
i nt age, wei ght;
/ / The r est of pr ogr am f oll ows.
Looking at Data Type s
You might wonder why it is important to have so many variable types. After all, a number is just a number. C++ has more data types, however, than almost all other programming languages. The variable’s type is critical, but choosing the type among the many offerings is not as difficult as it might first seem.
The character variable is easy to understand. A character variable can hold only a single character. You cannot put more than a single character into a character variable.
Integers hold whole numbers. Although mathematicians might cringe at this definition, an integer is actually any number that does
Chapter 4 ♦ Variables and Literals
not contain a decimal point. All the following expressions are integers:
45 - 932 0 12 5421
Floating-point numbers contain decimal points. They are known as real numbers to mathematicians. Any time you have to store a salary, a temperature, or any other number that might have a fractional part (a decimal portion), you must store it in a floating- point variable. All the following expressions are floating-point numbers, and any floating-point variable can hold them:
45. 12 - 2344. 5432 0. 00 . 04594
Sometimes you have to keep track of large numbers, and sometimes you have to keep track of smaller numbers. Table 4.2 shows a list of ranges that each C++ variable type can hold.
Table 4.2. Typical ranges that C++ variables hold.
Type Range*
char –128 to 127
unsi gned char 0 to 255
si gned char –128 to 127
i nt –32768 to 32767
unsi gned i nt 0 to 65535
si gned i nt –32768 to 32767
shor t i nt –32768 to 32767
unsi gned shor t i nt 0 to 65535
EXAMPLE
Type Range*
si gned shor t i nt –32768 to 32767
l ong i nt –2147483648 to 2147483647
si gned l ong i nt –2147483648 to 2147483647
f l oat –3.4E–38 to 3.4E+38
doubl e –1.7E–308 to 1.7E+308
l ong doubl e –3.4E–4932 to 1.1E+4932
* Use this table only as a guide; different compilers and different computers can have different ranges.
Notice that long integers and long doubles tend to hold larger numbers (and therefore, have a higher precision) than regular integers and regular double floating-point variables. This is due to the larger number of memory locations used by many of the C++ compilers for these data types. Again, this is usually—but not always—the case.
Chapter 4 ♦ Variables and Literals
Generally, all numeric variables should be signed (the default) unless you know for certain that your data contain only positive numbers. (Some values, such as age and distances, are always positive.) By making a variable an unsigned variable, you gain a little extra storage range (as explained in Appendix A, “Memory Addressing, Binary, and Hexadecimal Review”). That range of values must always be positive, however.
Obviously, you must be aware of what kinds of data your variables hold. You certainly do not always know exactly what each variable is holding, but you can have a general idea. For example, in storing a person’s age, you should realize that a long integer variable would be a waste of space, because nobody can live to an age that can’t be stored by a regular integer.
At first, it might seem strange for Table 4.2 to state that character variables can hold numeric values. In C++, integers and character variables frequently can be used interchangeably. As explained in Appendix A, “Memory Addressing, Binary, and Hexa- decimal Review,” each ASCII table character has a unique number that corresponds to its location in the table. If you store a number in a character variable, C++ treats the data as if it were the ASCII character that matched that number in the table. Conversely, you can store character data in an integer variable. C++ finds that
EXAMPLE
character’s ASCII number, and stores that number rather than the character. Examples that help illustrate this appear later in the chapter.
Designating Long, Unsigned, and Floating-Point Literals
When you type a number, C++ interprets its type as the smallest type that can hold that number. For example, if you print 63, C++ knows that this number fits into a signed integer memory location. It does not treat the number as a long integer, because 63 is not large enough to warrant a long integer literal size.
However, you can append a suffix character to numeric literals to override the default type. If you put an L at the end of an integer, C++ interprets that integer as a long integer. The number 63 is an integer literal, but the number 63L is a long integer literal.
Assign the U suffix to designate an unsigned integer literal. The number 63 is, by default, a signed integer literal. If you type 63U, C++ treats it as an unsigned integer. The suffix UL indicates an unsigned long literal.
C++ interprets all floating-point literals (numbers that contain decimal points) as double floating-point literals (double float- ing-point literals hold larger numbers than floating-point liter- als). This process ensures the maximum accuracy in such numbers. If you use the literal 6. 82 , C++ treats it as a double floating-point data type, even though it would fit in a regular f l oat . You can append the floating-point suffix (F) or the long double floating-point suffix (L) to literals that contain decimal points to represent a floating-point literal or a long double floating-point literal.
You may rarely use these suffixes, but if you have to assign a literal value to an extended or unsigned variable, your literals might be a little more accurate if you add U, L, UL, or F (their lowercase equivalents work too) to their ends.
Chapter 4 ♦ Variables and Literals
Assigning Values to Variable s
Now that you know about the C++ variable types, you are ready to learn the specifics of assigning values to those variables. You do this with the assignment statement. The equal sign (=) is used for assigning values to variables. The format of the assignment statement is
var i abl e=expressi on;
The var i abl e is any variable that you declared earlier. The expr essi on is any variable, literal, expression, or combination that produces a resulting data type that is the same as the var i abl e ’s data type.
Examples
- If
you want to keep track of your current age, salary, and dependents, you could store these values in three C++ variables. You first declare the variables by deciding on correct types and good names for them. You then assign values to them. Later in the program, these values might change (for example, if the program calculates a new pay increase for you).
Good variable names include age, sal ar y , and dependent s . To declare these three variables, the first part of the mai n() function would look like this:
/ / Decl ar e and st or e t hr ee val ues. mai n( )
{
i nt age;
f l oat sal ar y;
i nt dependent s;
EXAMPLE
Notice that you do not have to declare all integer variables together. The next three statements assign values to the variables.
age=32;
sal ar y=25000. 00; dependent s=2;
/ / Rest of pr ogr am f oll ows.
This example is not very long and doesn’t do much, but it illustrates the using and assigning of values to variables.
- Do
not put commas in values that you assign to variables. Numeric literals should never contain commas. The follow- ing statement is invalid:
sal ary=25, 000. 00;
- You can assign variables or mathematical expressions to other
variables. Suppose, earlier in a program, you stored your tax rate in a variable called t ax_r at e , then decided to use your tax rate for your spouse’s rate as well. At the proper point in the program, you would code the following:
spouse_t ax_r at e = t ax_r at e;
(Adding spaces around the equal sign is acceptable to the C++ compiler, but you do not have to do so.) At this point in the program, the value in t ax_r at e is copied to a new variable named spouse_t ax_r at e . The value in t ax_r at e is still there after this line finishes. The variables were declared earlier in the program.
If your spouse’s tax rate is 40 percent of yours, you can assign an expression to the spouse’s variable, as in:
spouse_t ax_r at e = t ax_r at e * . 40;
Any of the four mathematical symbols you learned in the previous chapter, as well as the additional ones you learn later in the book, can be part of the expression you assign to a variable.
Chapter 4 ♦ Variables and Literals
- If
you want to assign character data to a character variable, you must enclose the character in single quotation marks. All C++ character literals must be enclosed in single quota- tion marks.
The following section of a program declares three variables, then assigns three initials to them. The initials are character literals because they are enclosed in single quotation marks.
mai n( )
{
char f i r st , mi ddl e, l ast; f i r st = ‘ G’ ;
mi ddl e = ‘ M’ ; l ast = ‘ P’ ;
/ / Rest of pr ogr am f oll ows.
Because these are variables, you can reassign their values later if the program warrants it.