Monday 14 October 2013

Variables and Constants IN C++

Day 3

Variables and Constants

Programs need a way to store the data they use. Variables and constants offer various ways to represent and manipulate that data.
Today you will learn
  • How to declare and define variables and constants.
  • How to assign values to variables and manipulate those values.
  • How to write the value of a variable to the screen.

What Is a Variable?

In C++ a variable is a place to store information. A variable is a location in your computer's memory in which you can store a value and from which you can later retrieve that value.
Your computer's memory can be viewed as a series of cubbyholes. Each cubbyhole is one of many, many such holes all lined up. Each cubbyhole--or memory location--is numbered sequentially. These numbers are known as memory addresses. A variable reserves one or more cubbyholes in which you may store a value.
Your variable's name (for example, myVariable) is a label on one of these cubbyholes, so that you can find it easily without knowing its actual memory address. Figure 3.1 is a schematic representation of this idea. As you can see from the figure, myVariable starts at memory address 103. Depending on the size of myVariable, it can take up one or more memory addresses.

Setting Aside Memory

When you define a variable in C++, you must tell the compiler what kind of variable it is: an integer, a character, and so forth. This information tells the compiler how much room to set aside and what kind of value you want to store in your variable.
Each cubbyhole is one byte large. If the type of variable you create is two bytes in size, it needs two bytes of memory, or two cubbyholes. The type of the variable (for example, integer) tells the compiler how much memory (how many cubbyholes) to set aside for the variable.
Because computers use bits and bytes to represent values, and because memory is measured in bytes, it is important that you understand and are comfortable with these concepts. For a full review of this topic, please read Appendix B, "C++ Keywords."

Size of Integers

On any one computer, each variable type takes up a single, unchanging amount of room. That is, an integer might be two bytes on one machine, and four on another, but on either computer it is always the same, day in and day out.
char variable (used to hold characters) is most often one byte long. A short integer is two bytes on most computers, a long integer is usually four bytes, and an integer (without the keyword short or long) can be two or four bytes. Listing 3.1 should help you determine the exact size of these types on your computer.

Listing 3.1. Determining the size of variable types on your computer.
1:   #include <iostream.h>
2:
3:   int main()
4:   {
5:     cout << "The size of an int is:\t\t"    << sizeof(int)    << " bytes.\n";
6:     cout << "The size of a short int is:\t" << sizeof(short)  << " bytes.\n";
7:     cout << "The size of a long int is:\t"  << sizeof(long)   << " bytes.\n";
8:     cout << "The size of a char is:\t\t"    << sizeof(char)   << " bytes.\n";
9:     cout << "The size of a float is:\t\t"   << sizeof(float)  << " bytes.\n";
10:    cout << "The size of a double is:\t"    << sizeof(double) << " bytes.\n";
11:
12:        return 0;
13: }
Output: The size of an int is:          2 bytes.
The size of a short int is:     2 bytes.
The size of a long int is:      4 bytes.
The size of a char is:          1 bytes.
The size of a float is:         4 bytes.
The size of a double is:        8 bytes.


signed and unsigned

In addition, all integer types come in two varieties: signed and unsigned. The idea here is that sometimes you need negative numbers, and sometimes you don't. Integers (short and long) without the word "unsigned" are assumed to be signedSigned integers are either negative or positive. Unsigned integers are always positive.
Because you have the same number of bytes for both signed and unsigned integers, the largest number you can store in an unsigned integer is twice as big as the largest positive number you can store in a signedinteger. An unsigned short integer can handle numbers from 0 to 65,535. Half the numbers represented by a signed short are negative, thus a signed short can only represent numbers from -32,768 to 32,767. If this is confusing, be sure to read Appendix A, "Operator Precedence."

Fundamental Variable Types

Several other variable types are built into C++. They can be conveniently divided into integer variables (the type discussed so far), floating-point variables, and character variables.
Floating-point variables have values that can be expressed as fractions--that is, they are real numbers. Character variables hold a single byte and are used for holding the 256 characters and symbols of the ASCII and extended ASCII character sets.
Table 3.1. Variable Types.
TypeSizeValues
unsigned short int2 bytes0 to 65,535
short int2 bytes-32,768 to 32,767
unsigned long int4 bytes0 to 4,294,967,295
long int4 bytes-2,147,483,648 to 2,147,483,647
int (16 bit)2 bytes-32,768 to 32,767
int (32 bit)4 bytes-2,147,483,648 to 2,147,483,647
unsigned int (16 bit)2 bytes0 to 65,535
unsigned int (32 bit)2 bytes0 to 4,294,967,295
char1 byte256 character values
float4 bytes1.2e-38 to 3.4e38
double8 bytes2.2e-308 to 1.8e308

Defining a Variable

You create or define a variable by stating its type, followed by one or more spaces, followed by the variable name and a semicolon. The variable name can be virtually any combination of letters, but cannot contain spaces. Legal variable names include xJ23qrsnf, and myAge. Good variable names tell you what the variables are for; using good names makes it easier to understand the flow of your program. The following statement defines an integer variable called myAge:
int myAge;
As a general programming practice, avoid such horrific names as J23qrsnf, and restrict single-letter variable names (such as x or i) to variables that are used only very briefly. Try to use expressive names such as myAgeor howMany. Such names are easier to understand three weeks later when you are scratching your head trying to figure out what you meant when you wrote that line of code.
Try this experiment: Guess what these pieces of programs do, based on the first few lines of code:
Example 1
main()
{
     unsigned short x;
     unsigned short y;
     ULONG z;
     z = x * y;
}
Example 2
main ()
{
     unsigned short Width;
     unsigned short Length;
     unsigned short Area;
     Area = Width * Length;
}
Clearly, the second program is easier to understand, and the inconvenience of having to type the longer variable names is more than made up for by how much easier it is to maintain the second program.

Case Sensitivity

C++ is case-sensitive. In other words, uppercase and lowercase letters are considered to be different. A variable named age is different from Age, which is different from AGE.

Keywords

Some words are reserved by C++, and you may not use them as variable names. These are keywords used by the compiler to control your program. Keywords include ifwhilefor, and main. Your compiler manual should provide a complete list, but generally, any reasonable name for a variable is almost certainly not a keyword.

Creating More Than One Variable at a Time

You can create more than one variable of the same type in one statement by writing the type and then the variable names, separated by commas. For example:
unsigned int myAge, myWeight;   // two unsigned int variables
long area, width, length;       // three longs
As you can see, myAge and myWeight are each declared as unsigned integer variables. The second line declares three individual long variables named areawidth, and length. The type (long) is assigned to all the variables, so you cannot mix types in one definition statement.

Assigning Values to Your Variables

You assign a value to a variable by using the assignment operator (=). Thus, you would assign 5 to Width by writing
unsigned short Width;
Width = 5;
You can combine these steps and initialize Width when you define it by writing
unsigned short Width = 5;
Initialization looks very much like assignment, and with integer variables, the difference is minor. Later, when constants are covered, you will see that some values must be initialized because they cannot be assigned to. The essential difference is that initialization takes place at the moment you create the variable.
Just as you can define more than one variable at a time, you can initialize more than one variable at creation. For example:
// create two long variables and initialize them
Ă‚long width = 5, length = 7;  
This example initializes the long integer variable width to the value 5 and the long integer variable length to the value 7. You can even mix definitions and initializations:
int myAge = 39, yourAge, hisAge = 40;
This example creates three type int variables, and it initializes the first and third.
Listing 3.2 shows a complete program, ready to compile, that computes the area of a rectangle and writes the answer to the screen.
Listing 3.2. A demonstration of the use of variables.
1:   // Demonstration of variables
2:   #include <iostream.h>
3:
4:   int main()
5:   {
6:     unsigned short int Width = 5, Length;
7:     Length = 10;
8:
9:     // create  an unsigned short and initialize with result
10:       // of multiplying Width by Length
11:     unsigned short int Area  = Width * Length;
12:
13:     cout << "Width:" << Width << "\n";
14:     cout << "Length: "  << Length << endl;
15:     cout << "Area: " << Area << endl;
16:        return 0;
17: }
Output: Width:5
Length: 10
Area: 50

typedef

It can become tedious, repetitious, and, most important, error-prone to keep writing unsigned short int. C++ enables you to create an alias for this phrase by using the keyword typedef, which stands for type definition.
In effect, you are creating a synonym, and it is important to distinguish this from creating a new type (which you will do on Day 6). typedef is used by writing the keyword typedef, followed by the existing type and then the new name. For example
typedef unsigned short int USHORT
creates the new name USHORT that you can use anywhere you might have written unsigned short int. Listing 3.3 is a replay of Listing 3.2, using the type definition USHORT rather than unsigned short int.
Listing 3.3. A demonstration of typedef.
1:   // *****************
2:   // Demonstrates typedef keyword
3:   #include <iostream.h>
4:
5:   typedef unsigned short int USHORT;       //typedef defined
6:
7:   void main()
8:   {
9:     USHORT  Width = 5;
10:    USHORT Length;
11:    Length = 10;
12:    USHORT Area  = Width * Length;
13:    cout << "Width:" << Width << "\n";
14:    cout << "Length: "  << Length << endl;
15:    cout << "Area: " << Area <<endl;
16: }
Output: Width:5
Length: 10
Area: 50


Wrapping Around an unsigned Integer

The fact that unsigned long integers have a limit to the values they can hold is only rarely a problem, but what happens if you do run out of room?
When an unsigned integer reaches its maximum value, it wraps around and starts over, much as a car odometer might. Listing 3.4 shows what happens if you try to put too large a value into a short integer.
Listing 3.4.A demonstration of putting too large a value in an unsigned integer.
1: #include <iostream.h>
2:  int main()
3:  {
4:     unsigned short int smallNumber;
5:     smallNumber = 65535;
6:     cout << "small number:" << smallNumber << endl;
7:     smallNumber++;
8:     cout << "small number:" << smallNumber << endl;
9:     smallNumber++;
10:    cout << "small number:" << smallNumber << endl;
11:        return 0;
12: }
Output: small number:65535
small number:0
small number:1


Wrapping Around a signed Integer

signed integer is different from an unsigned integer, in that half of the values you can represent are negative. Instead of picturing a traditional car odometer, you might picture one that rotates up for positive numbers and down for negative numbers. One mile from 0 is either 1 or -1. When you run out of positive numbers, you run right into the largest negative numbers and then count back down to 0. Listing 3.5 shows what happens when you add 1 to the maximum positive number in an unsigned short integer.
Listing 3.5. A demonstration of adding too large a number to a signed integer.
1:  #include <iostream.h>
2:  int main()
3:  {
4:     short int smallNumber;
5:     smallNumber = 32767;
6:     cout << "small number:" << smallNumber << endl;
7:     smallNumber++;
8:     cout << "small number:" << smallNumber << endl;
9:     smallNumber++;
10:    cout << "small number:" << smallNumber << endl;
11:        return 0;
12: }
Output: small number:32767
small number:-32768
small number:-32767


Characters

Character variables (type char) are typically 1 byte, enough to hold 256 values (see Appendix C). A char can be interpreted as a small number (0-255) or as a member of the ASCII set. ASCII stands for the American Standard Code for Information Interchange. The ASCII character set and its ISO (International Standards Organization) equivalent are a way to encode all the letters, numerals, and punctuation marks.

Characters and Numbers

When you put a character, for example, `a', into a char variable, what is really there is just a number between 0 and 255. The compiler knows, however, how to translate back and forth between characters (represented by a single quotation mark and then a letter, numeral, or punctuation mark, followed by a closing single quotation mark) and one of the ASCII values.
The value/letter relationship is arbitrary; there is no particular reason that the lowercase "a" is assigned the value 97. As long as everyone (your keyboard, compiler, and screen) agrees, there is no problem. It is important to realize, however, that there is a big difference between the value 5 and the character `5'. The latter is actually valued at 53, much as the letter `a' is valued at 97.
Listing 3.6. Printing characters based on numbers
1:   #include <iostream.h>
2:   int main()
3:   {
4:   for (int i = 32; i<128; i++)
5:         cout << (char) i;
6:         return 0;
7: }

Table 3.2. The Escape Characters.
CharacterWhat it means
\nnew line
\ttab
\bbackspace
\"double quote
\'single quote
\?question mark
\\backslash

Constants

Like variables, constants are data storage locations. Unlike variables, and as the name implies, constants don't change. You must initialize a constant when you create it, and you cannot assign a new value later.

Literal Constants

C++ has two types of constants: literal and symbolic.
A literal constant is a value typed directly into your program wherever it is needed. For example
int myAge = 39;
myAge is a variable of type int39 is a literal constant. You can't assign a value to 39, and its value can't be changed.

Symbolic Constants

A symbolic constant is a constant that is represented by a name, just as a variable is represented. Unlike a variable, however, after a constant is initialized, its value can't be changed.
If your program has one integer variable named students and another named classes, you could compute how many students you have, given a known number of classes, if you knew there were 15 students per class:
students = classes * 15;


Summary

This chapter has discussed numeric and character variables and constants, which are used by C++ to store data during the execution of your program. Numeric variables are either integral (charshort, and long int) or they are floating point (float and double). Numeric variables can also be signed or unsigned. Although all the types can be of various sizes among different computers, the type specifies an exact size on any given computer.
Goto Main Menu....

No comments:

Post a Comment