Previous Page TOC Next Page



- 5 -
Numbers and Characters


variables


What You'll Learn About


Computers can store data in many different formats. Visual C++ works with that data and, through programs you write, processes it into information the user needs. In Lesson 2, "Analyzing Visual C++ Programs," you learned that programs consist of data and commands. You must learn to store that data properly so that your programs can manage it properly. Visual C++ uses constants and variables to hold data your programs need.

The term data is the plural of datum. As is common in many texts these days, this book uses the word data to mean both the plural and the singular. Accuracy in English is almost as important as accuracy in programming, but moving between the terms datum and data often results in more confusion than clarity.

Data and Information




Although the terms are often used interchangeably, data and information have two different meanings.

Is there a difference between data and information? Maybe you have not thought too much about the two words and their meanings. Although most people think they have a good idea of what data and information mean, when asked to define them, people often use one to define the other, saying "Data is information" or "Information is data." As this section points out, there is a difference.

definition

Data processing (DP) is simply the processing of data into meaningful information.

You might have heard the term data processing. At its simplest level, that's what the computer does best and does quickly. Figure 5.1 shows the basic model of every computer program ever written. The computer takes data as input, processes the data, and produces meaningful information as output.

Figure 5.1. The basic input-process-output model.

Think of a corporate president's information needs. Does the president want to get a daily list of the salaries of each of the company's 5,000 employees, down to the lowest-paid part-time clerk? Of course not. A list of every employee would be just raw facts and figures that the president does not have time to deal with. To the president, the list would be a waste of time.

The president certainly is concerned with payroll, but he or she needs meaningful information, not a bunch of raw facts and figures (data). The president might prefer a computerized graphic that shows such things as the payroll trends over the past year, how the company's payroll figures match those of the competitors, and how one department's payroll compares to another's. Data organized in such a fashion is information for the president—something he or she can use to make a decision. Computers are the perfect tools for processing all the data and producing meaningful information used by people who make decisions based on that information.



What is data to one person might be information to another. Would the part-time clerk care about the detailed payroll figure for his or her job? If so, wouldn't the salary for part-time clerks be important information to the clerk?



Data is made up of raw facts and figures. Information is processed data that provides meaning for people.



There is no Stop and Type part here due to this section's textual nature.


Data in a Visual C++ Program




Learn about the numeric and character data capabilities of C++.

definition

GIGO means garbage in, garbage out. You can't get good results from bad data.

Representing data properly should be the goal of every Visual C++ programmer. If the data is bad, GIGO results in bad output. A computer is not magic. It simply follows your program instructions and processes data with the commands you give it. If you give it bad data, it will produce bad results.

A Visual C++ program can process many kinds of data, but all Visual C++ data falls into these two broad categories:

This unit explains the numeric data types. The next unit, "String Data and I/O," explains the character data types. You do not have to be a mathematician to understand numeric data in a Visual C++ program. Let the computer do all the math! You want meaningful results, and it is the computer's job to take your data and produce meaningful results based on the instructions you supply.

In the second lesson, you learned about variables. You also saw programs that contained several literals (sometimes called constants). A variable is a storage location that holds a value. The contents of variables can change. Literals are numbers or character data that do not change.



C++ supports numeric and character data. The more effort that your programs spend checking data values for accuracy, the better assured you can be of the program's resulting output.



There is no Stop and Type part here due to this section's textual nature.


Characteristics of Variables




All variables share common characteristics. To use variables, you must first learn how to specify the variable's characteristics.

Whenever your program needs to store some data temporarily, you store that data in a variable. You also can store data in a file for long-term storage, but during a program's execution, variables are the primary place you put data until you are ready to use it. You, the programmer, are responsible for telling the program when it needs a variable. Before you use a variable, you must define it. When you define a variable, you tell Visual C++ to reserve some storage for that variable and give it a name. Any time after a variable is defined, you can place values into that variable.

In Visual C++, you can place variable definitions anywhere in the program, as long as the program does not use the variables until after they are defined. To define a variable, you must understand these characteristics that all variables share:


Naming Rules for Variables


You must assign and use variable names in a program to distinguish the variables from each other. Variable names must be unique; you cannot have two variables with the same name in the same program. (Actually, you will learn about an exception to this rule in Lesson 8, "Break It Up With Functions." For now, assume that all variable names in the same program must be unique.) Here are the naming rules for variables:

The Visual C++ compiler lets you start variable names with a leading underscore, but this practice is not recommended. Some of Visual C++'s built-in variable names begin with an underscore, and you might accidentally use Visual C++'s variable names for your own variables.



Some Visual C++ programmers use underscore characters in variable names to separate parts of the name, such as Sales_div1. Others prefer a hump notation, such as salesDiv1. The term hump notation is perfect for describing the uppercase letter (the hump) in the middle of the variable name that resemble a camel's hump.

The following variable names are valid names because they follow the naming rules:


sales     x_211     d     ageLimit     Amount95

Visual C++ programmers generally use lowercase letters for variable names, saving uppercase for the secondary words within a variable's name. When a variable name is a combination of two or more words, such as numOfEmps, it is common to uppercase the first letter of each word. Never uppercase every letter in a variable name, because some Visual C++ programmers reserve uppercase names for constant data that does not change or an old-style C programming feature called macros. (You will read about constants later in this unit.) Programmers also use the case of the first letter to help distinguish between function names, which by convention start with an uppercase letter, (but remember C++ itself is not aware of this convention).

Some programs have variables on 95 percent of their code lines. Because of the importance and abundance of variables, take the time to learn what makes a valid variable name and what makes an invalid variable name. You must know the naming rules of a variable before moving on.

You do not have to follow the uppercase/lowercase 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 Visual C++ compiler:

amount Amount AMOUNT aMOUNT

Never give a variable the same name as a Visual C++ command. Appendix D, "Visual C++ Command Reference," is a list of all the Visual C++ command names. If you inadvertently give a variable the same name as a command, such as while, the Visual C++ compiler will become confused and will not compile your program correctly. However, a variable name can contain a command without getting confused (so waitwhileprocessing would be a valid name).

Always use meaningful variable names. Give your variables names that help describe the values that they hold. For example, keeping track of chemistry weights in a variable called chemWeights is much more descriptive than using the variable name XYZ34. Even though both names are valid, chemWeights is easier to remember, and you get a good idea of what the variable holds by looking at its name.

Although you can and should use meaningful names, using names that are too long means too much typing and difficult to follow formulas.

Data Types


There are many different types of data, and you need different types of variables to hold them. Table 5.1 lists all the different types of Visual C++ variables. For instance, if a variable holds an integer, Visual C++ assumes that no decimal point or fractional part (the part to the right of the decimal point) exists for the variable's value.

Table 5.1. The Visual C++ variable data types.

Declaration Name Data Type Description
char Character
unsigned char Unsigned character
signed char Signed character (same as char)
int Integer
unsigned int Unsigned integer
signed int Signed integer (same as int)
short int Short integer
unsigned short int Unsigned short integer
signed short int Signed short integer (same as short int)
long Long integer
long int Long integer (same as long)
signed long int Signed long integer (same as long int)
unsigned long int Unsigned long integer
float Floating-point (real)
double Double floating-point (real)
long double Long double floating-point (real)

The data type of the variable you use depends on the data you store in it. The following sections more fully describe these types. Concentrate on how to define variables before worrying about how to use variables for data storage.

Defining Variables


definition

A local variable is a variable that belongs to the function with which it is declared.

When you define a variable, you place your order for Visual C++ to create a named space for that variable. Visual C++ does not care where you define a variable in a program, as long as you define it somewhere before the code that uses it. Local variables are by far the most common types of variables in Visual C++ programs, and they are the only kinds of variables you will see for much of this book. You can define variables either within the curly braces that mark the start and end of functions (remember that main() is what we called a function) or outside the braces.

definition

A global variable is a variable that you define outside any function, which can be seen and used by all following functions.

Variables are easy to define. To define a variable, you must state its type, followed by its name. In Lesson 2, you saw a program that defined four variables in the following way:


void main()

  {

    int age, weight;   // These lines define four variables

    char initial;

    float salary;

    // Rest of program follows

These lines define two local integer variables named age and weight, a character variable named initial, and a floating-point variable named salary. You have no idea what is inside these variables, however. Generally, you cannot assume that a variable holds zero, or any other number, until you assign it a value. Unlike most other languages, C++ does not automatically initialize variables (BASIC sets new numbers to zero). Values of variables are never remembered from one execution of the program to another.

The code also defines a character variable called initial. Put only single characters in character variables. Next, a floating-point variable called salary is defined.

After these four variable definitions, Visual C++ reserves storage in memory, assigns the variable names to the four reserved locations, and waits for you to put data in the variables. Until you place data in the variables, you do not know what their values are, so do not use them for anything initially except to store data in them.

Many Data Types


There are many different types of data, and Visual C++ wants to have a data type available to hold any data you might need to store. Visual C++ has more data types than almost any other programming language. When you need to store data, you need to pick the right variable data type. Numeric variables hold numbers and character variables hold single characters.

definition

An array is an aggregate data type that's a collection of individual data types.



You can't hold more than a single character in a Visual C++ character variable. To store a string of characters, you must use an array. The next unit describes how to represent string data.

Integers can hold only numbers that have no decimal point. These are sometimes called whole numbers. All of the following values are numeric integers:


33     -1     0      1     -83421

Store real numbers (numbers with decimal points) in floating-point variables. 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 of the following expressions are floating-point numbers, and any floating-point variable can hold them:


145.7722   0.00    -2344.5     4.00004

Each of the types of variables holds a different range of variables. Table 5.2 shows a list of typical ranges that each Visual C++ variable type can hold.

Table 5.2. Ranges of Visual C++ variables.

Type Range
char –128 to 127
unsigned char 0 to 255
signed char –128 to 127
int –32768 to 32767
unsigned int 0 to 65535
signed int –32768 to 32767
short int –32768 to 32767
unsigned short int 0 to 65535
signed short int –32768 to 32767
long int –2147483648 to 2147483647
signed long int –2147483648 to 2147483647
unsigned long 0 to 4294967296
float –3.4E38 to 3.4E+38
double –1.7E308 to 1.7E+308
long double –3.4E4932 to 1.1E+4932
float –3.4E+38 to 3.4E+38
double –1.7E+308 to 1.7E+308
long double –3.4E+4932 to 1.1E+4932


The unsigned variable types can hold only positive numbers, but they can hold larger positive values than the signed ones.

Table 5.2 holds true for Visual C++ with this book, but it might not hold true for other kinds of C++ compilers, even the latest Microsoft C++ compiler for the latest versions of Windows. In Visual C++, integers and character variables frequently can be used interchangeably. As shown in Appendix B, "The ASCII Table," 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, Visual C++ treats the data as if it were the ASCII character that matches that number in the table. Conversely, you can store character data in an integer variable. Visual C++ finds that character's ASCII number and stores that number rather than the character. Examples that help illustrate this point appear later in this unit.

definition

Scientific notation is a shortcut method for representing extremely large or small values.

You might think that some of the floating-point ranges from Table 5.2 look strange with their E notation. The E represents scientific notation. To determine what value each number represents, take the number before the E (meaning Exponent) and multiply it by 10 raised to the power after the plus sign. For instance, a floating-point number (type float) can contain a number as small as –3.4E+38.

Long integers and long doubles can 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 Visual C++ for these data types.



Every time your computer has to access more storage for a single variable (as is usually the case for long variables), it takes the computer much longer to access it, perform calculations, and store it. Use the long variables only if you suspect your data might overflow the typical data type ranges. Although the ranges differ between computers, you should have an idea of whether your numbers might exceed the computer's storage ranges. If you are working with extremely large (or extremely small and fractional) numbers, you should consider using the long and double variables.

Most numeric variables should be signed unless you know for certain that your data contains only positive numbers. (Some values, such as age and distances, are always positive.) By making a variable unsigned, you gain a little extra storage range. That range of values, however, must always be positive. 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 yet live longer than the largest value a regular integer can hold. These two variable definitions are exactly the same:


int i = 7;

and


signed int i = -7;

But they are not the same as this:


unsigned int i = -7;   // Unsigned variables can't hold negatives


C++ does not check whether the values you assign into a number will fit and will not produce an error if you exceed the maximum value that a field can hold.

Listing 5.1 contains a fragment of a Visual C++ program that defines four variables.



When you define variables, use meaningful variable names and assign a data type that matches the data you store in the variable.

input

Input Listing 5.1. Defining variables.

1:  void main()

2:  {

3:    char regionCode;

4:    int numEmployees;

5:    long int numCustomers;

6:    double yearlySales;

Output

There is no output from this fragment of code.

Analysis

The four variables defined in Listing 5.1 are local variables because they are all defined after an opening brace. Line 3 defines a character variable that will hold one character. A character variable can always hold one character at most. The character might be a letter, digit, or special character such as & or #.

The listing defines two integer variables. The first integer named numEmployees is defined on line 4. numEmployees is a regular integer variable. Line 5's numCustomers is a long integer value because it can hold a number larger than 32767 (the maximum value that a regular integer can hold as pointed out in Table 5.2).

The yearlySales variable, defined on line 6, is large enough to hold a huge floating-point number.

Literals




You specify literals in different ways depending on their data type.

definition

Literals are text representations in the program that do not change. They are used as values by the program.

There are several types of Visual C++ literals. Literals do not change. Integer literals are whole numbers that do not contain decimal points. Floating-point literals are numbers that contain a fractional portion (a decimal point with an optional value to the right of the decimal point).

Integer Literals


Visual C++ enables you to assign integer literals to variables, use integer literals for calculations, and print integer literals using the cout operator. All of the following numbers are integer literals:


1  34  -56


In most programming languages, literals are sometimes called constants. In C++, however, the term constant has a specific meaning as you'll see at the end of this unit. Therefore, this book sticks to using literal for nonvariable values that represent numeric, character, and string data.

Never precede an integer with a leading 0 unless you want Visual C++ to interpret the number as base-16 or base-8.

Hexadecimal (base-16) is a numbering system used for internal data. To represent a hexadecimal integer literal, add the 0x prefix to it. The following numbers are hexadecimal numbers:


0x13     0xF6C9     0x401     0XFFFFF

The x and hexadecimal letters can be any mixture of lowercase and uppercase.

A leading 0 before a number, without the x, indicates that the literal is an octal (base-8) number. Base-8 is not used much today. The following literals are base-8 literals because they begin with a leading 0:


044     05     01     076     004

If you write business-application programs in Visual C++, you might think that you will never have the need for hexadecimals, and you might be correct.

You can begin floating-point literals with a leading zero, for example, 0.9. They are properly interpreted by Visual C++. You can't have hexadecimal or octal floating-point literals, so the leading zero is sometimes used to specify precision in floating-point literals.

Long, Unsigned, and Floating-Point Literals


When you use a literal integer in a program, Visual C++ interprets its data type as the smallest type that can hold that number. For example, if you type 13, Visual C++ knows that this number fits into a signed integer memory location. It does not treat the number as a long integer, because 13 is not large enough to warrant a long integer literal size.

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, Visual C++ interprets that integer as a long integer. The number 13 is an integer literal, but the number 13L is a long integer literal. For example, you might want to add the L if you were adding a number to a long integer variable.

Assign the U suffix to designate an unsigned integer literal. The number 13 is, by default, a signed integer literal. If you type 13U, Visual C++ treats it as an unsigned integer. The suffix UL indicates an unsigned long literal.

Visual C++ interprets all floating-point literals (numbers that contain decimal points) as double floating-point literals (double floating-point literals hold larger numbers than floating-point literals). This process ensures the maximum accuracy for such numbers. If you use the literal 32.05, Visual C++ treats it as a double floating-point data type, even though it would fit in a regular float. You can append the floating-point suffix 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 might not use these suffixes often, 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 append a U, L, UL, or F (their lowercase equivalents also work).

Putting Data in Variables


It is easy to fill variables with data. The equal sign (=) is used for assigning values to variables. The format of an assignment is


variable = expression;

The variable is a variable name that you defined earlier in the program. The expression is any variable, literal, expression, or combination that produces a resulting data type that is the same as the variable's data type.



Putting spaces around the equal sign makes it more readable, but the C++ compiler does not require them.



The equal sign means that you want to take the number, variable, or expression on the right side of the equal sign and put it into the variable on the left.

Consider a program that tracks your company's Top 100 ranking, monthly sales, and years in business. You could store these values in three Visual C++ variables. First you would define the variables by deciding on correct types and choosing descriptive names for them. You would then assign them values. Later in the program, these values might change (for example, if the program were to calculate a new pay increase for you).

Here is the code that defines these variables:


void main()

  {

    int ranking, years;

    float sales;

The next three statements assign values to the variables:


    ranking = 79;

    sales = 65750.93;

    years = 14;

// Rest of program would follow


Never put commas in values that you assign to variables. The following statement is invalid:


sales = 65,750.93;  // Don't do this!

Any expression can go to the right of the equal sign as long as it matches the type of variable on the left. Suppose that, earlier in a program, you stored your tax rate in a variable called taxRate, and 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:


spouseTaxRate = taxRate;

At this point in the program, the value in taxRate is copied to a new variable named spouseTaxRate. The value in taxRate is still there after this line finishes. The variables were declared earlier in the program.

If your spouse's tax rate is 32 percent of yours, you can assign an expression to the spouse's variable, like so:


spouseTaxRate = taxRate * .32;  // Compute 32% of a tax rate

You must enclose character literals in single quotation marks if you want to assign character data to character variables. The following section of a program declares three variables, and then assigns three initials to them:


char first, middle, last;

first = 'F';

middle = 'I';

last = 'Q';

Visual C++ allows a shortcut for defining variables and then placing values in them. The following program both defines and initializes three variables at the same time.


char initial = 'G';   // Defines and initializes

// at the same time

int books = 230;

float price = 23.95;


Remember that a C++ variable is not initialized; it will contain random garbage. Good practice is to always initialize a variable as soon as it is declared.



Visual C++ prefers that you store matching data values in the proper variables. Although you can assign a character literal to a floating-point variable, you should not do so. Sometimes Visual C++ will not allow it. There are ways that you can safely mix types, and this book explains when you can.

Listing 5.2 contains the variable definitions for a character and one floating-point value.



Store data values in variables using the assignment operator, =. You can assign initial values to variables when you define the variables or later in the program.

input

Input Listing 5.2. Putting data in variables.

1:  void main()

2:   {

3:    int i;

4:    char c = 'P';

5:    // Some program code goes here

6:    i = 35 * 14;

output

Lines 3 and 4 define an integer and a character variable. Line 3 defines the integer named i without storing an initial value in i. Later, on line 6, i is assigned the result of a calculation.

Line 4 defines a character variable named c and, at the same time, the literal value of P is stored in the variable. You must enclose all character literals inside single quotation marks.



The single quotation marks are not part of the data stored in character variables. The single quotation marks serve only to specify character literals.


Constant Variables




Using const, you can define variables whose values never change.

You might think that the term constant variable sounds like a contradiction. After all, a constant never changes, and a variable holds values that change. Visual C++ constant variables, often called just constants, are different from what is termed a constant in other programming languages. In most programming languages, a constant is the same thing as a literal. Although some Visual C++ programmers use the words interchangeably, a literal is, technically speaking, reserved for data values that are typed directly into a program and do not change. Constants are the special variables described as follows.

In Visual C++ terminology, you can declare variables to be constants with the const keyword. Throughout your program, the constants act like variables; you can use a constant variable anywhere you can use a variable, but you cannot change constant variables. To declare a constant, put the keyword const in front of the variable declaration, like so:


const int ageLimit = 21;

You must put an initial value into the constant variable. If you don't, Visual C++ will never let you assign it a value later because you cannot do anything to change the value of a constant.

Any type of variable can be made a constant. Visual C++ offers the const keyword as an improvement of the #define preprocessor directive that C uses. A #define directive specifies that whenever a character string is found in the code, it should be replaced by another character string. This makes it a quick and easy way to substitute the same value throughout the code without retyping the literal. Although Visual C++ supports #define as well, const enables you to specify constant values with specific data types.



If you omit the data type of a constant variable, Visual C++ assumes that it is an integer. Therefore, the following two lines are equivalent:

const int ageLimit = 21;

and


const ageLimit = 21;

Use const when you have data that does not change but to which you want to assign a name. For example, a minimum sales level would be a good candidate for a constant. If you accidentally attempt to change a constant, Visual C++ will let you know.

Another advantage to named constant variables is that, if your program's environment changes and you must change the value initially assigned to the constant, you make the change in one place. If, instead, you typed the value throughout the program, you would have to change that value everywhere it appeared, as well as place a comment about the meaning of the literal at each use.

Listing 5.3 contains a program fragment, which contains two statements that define constant variables.



Use const when you want to name a value that does not change.

input

Input Listing 5.3. Defining two constant variables.

1:  const int bonusLevel = 3000;

2:  const float e = 2.718282;

output

Line 1 defines and initializes a constant integer variable named bonusLevel. Nowhere in the rest of the program can a new value be assigned to bonusLevel.

Line 2 defines a floating-point constant variable. In mathematics, e has a special meaning and its value is approximately equal to 2.718282.

Homework



General Knowledge


  1. What are the two general types of data?

  2. What is another name for a literal?

  3. What are the numeric literal suffixes and what do they mean?

  4. What does Visual C++ do when you define a variable?

  5. What is the Visual C++ difference between a variable and a constant?

  6. What is the Visual C++ difference between a constant and a literal?

  7. What is the Visual C++ difference between a variable and a literal?

  8. What must you enclose character literals in?

  9. Why can you not specify an integer literal with a leading zero?

  10. Why can you never assign a value to a constant variable after you define it?

  11. Why should you use the smallest variable data type available that holds the data you need to hold?

  12. Which of the following are floating-point values?

    
    -0     -12     34.     34.0     34.4444444      -0.00001

  13. Which of the following integers are decimal, which are hexadecimal, and which are octal?


    
    0     05     0x15     250     0250     0x250

  14. What are the data types of each of these numbers?


    
    5     5.55     5L     5.55L

  15. If you were writing a program that tracked your financial records, which of the following generally are variable and which generally are constant?

    
    Your social security number
    
    Your age
    
    Your salary
    
    Your first name
    
    Your date of birth

  16. True or false: The following are identical:


    
    const int ageLimit = 21;

  17. and


    
    const ageLimit = 21;

  18. True or false: A variable can be a literal.

  19. True or false: You cannot begin a floating-point literal with a leading zero.

    Find the Bug


  20. What are the valid variable names from the following list?

    
    95Sales     sales#95     Sales95     _Sales_95    SALES_95
    
    sales(95)   95_Sales     Sales95Qtr  Sales()

  21. What is wrong with the following program fragment?

    
    // Program that stores values in variables
    
    void main()
    
    {
    
      int age;
    
      char letter = 45.43;
    
      age = 12.5;
    
      // Rest of program follows

  22. There are two errors in the first few lines of this program. What are they?

    
    // Program that uses a constant variable
    
    void main()
    
    {
    
      const SALARY = 234.54;
    
      const int age;
    
      AGE = 21;
    
      // Rest of program follows

    Write Code That. . .


  23. Rewrite the following lines of variable definitions so that the data types are grouped in a more orderly fashion:

    
    void main()
    
    {
    
      float height;
    
      int num1;
    
      char answer;
    
      float salary;
    
      int num2;
    
      // Rest of program follows

  24. Suppose that you are taking three classes at a local community college and you want to write a program to keep track of your letter grade and your numeric average in each class. To the following code fragment, add the variable definition lines that define the six variable names and their types.

    
    void main()
    
    {

  25. Rewrite the following three numbers so that they do not use scientific notation:

    
    2.3221E+4     2.3221E-4     -1.789E+2

  26. Suppose that you are to write a program for a driver's license agency and need to store the driving age limit of 16 in a constant integer variable. How will you define it?

    Extra Credit


  27. Write a constant variable definition that defines the mathematical value of Pi. Pi is approximately equal to 3.14159 and never changes.

Previous Page Page Top TOC Next Page