Variables

 

As has been stated in previous topics, variables have names or identifiers, and they also have values. Another important property of a variable is its data type. The data types are important because they determine the number of bytes of data storage in memory needed to hold the value.  The smallest data type is char and the widest data type is long double. You will find a comprehensive table of the data types at my Web Site under the link “C++ Reference Page”. There you will find a page called “Classes” and another page called “Namespaces”.  Using the latter link, and clicking on “Variables” will take you to the table where you will find that char is 8 bits wide, or one byte, whereas long double is 64 bits wide, or 8 bytes.

 

Just knowing the width of a variable is not enough to understand the relationship between its value and the format in which it is stored. For example, a long double and a double share the same width, 8 bytes, and yet the precision and the range of values possible in the two data types are quite different.

 

In order for the compiler to generate the proper low level code, it must keep track of what the data type is for each variable – otherwise, an incorrect library function may be scheduled to manipulate a variable or format it for display, and the result would be garbage. Therefore, when the variables are declared in the program, their data type is specified and that does not change for the life of the program.  There is no way that you can have a variable named senior that is declared as type bool and then re-typed to be of type float in some other part of the program. It should also be obvious that the declaration of the variable should appear in the listing before the variable is first used.

 

As you examine Listings 2-2 through 2-5, notice the order in which variables are declared and initialized and used. Also note how an integer is displayed versus a float.