![]() |
|||
|
|||
Defining a VariableYou 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 x, J23qrsnf, 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 myAge or 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 SensitivityC++ 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.
There are various conventions for how to name variables, and although it doesn't much matter which method you adopt, it is important to be consistent throughout your program. Many programmers prefer to use all lowercase letters for their variable names. If the name requires two words (for example, my car), there are two popular conventions: my_car or myCar. The latter form is called camel-notation, because the capitalization looks something like a camel's hump. Some people find the underscore character (my_car) to be easier to read, while others prefer to avoid the underscore, because it is more difficult to type. This guide uses camel-notation, in which the second and all subsequent words are capitalized: myCar, theQuickBrownFox, and so forth.
KeywordsSome 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 if, while, for, 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 TimeYou 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 longsAs you can see, myAge and myWeight are each declared as unsigned integer variables. The second line declares three individual long variables named area, width, and length. The type (long) is assigned to all the variables, so you cannot mix types in one definition statement. Assigning Values to Your VariablesYou 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: 50Analysis: Line 2 includes the required
include statement for the iostream's library so that cout
will work. Line 4 begins the program. On line 11, an unsigned short integer, Area, is defined, and it is initialized with the value obtained by multiplying Width times Length. On lines 13-15, the values of the variables are printed to the screen. Note that the special word endl creates a new line. typedefIt 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 Chapter 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 USHORTcreates 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: 50Analysis: On line 5, USHORT is typedefined as a synonym for unsigned short int. The program is very much like Listing 3.2, and the output is the same. When to Use short and When to Use longOne source of confusion for new C++ programmers is when to declare a variable to be type long and when to declare it to be type short. The rule, when understood, is fairly straightforward: If there is any chance that the value you'll want to put into your variable will be too big for its type, use a larger type. As seen in Table 3.1, unsigned short integers, assuming that they are two bytes, can hold a value only up to 65,535. Signed short integers can hold only half that. Although unsigned long integers can hold an extremely large number (4,294,967,295) that is still quite finite. If you need a larger number, you'll have to go to float or double, and then you lose some precision. Floats and doubles can hold extremely large numbers, but only the first 7 or 19 digits are significant on most computers. That means that the number is rounded off after that many digits. Wrapping Around an unsigned IntegerThe 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:1Analysis: On line 4, smallNumber
is declared to be an unsigned short int, which on my computer is a two-byte
variable, able to hold a value between 0 and 65,535. On line 5, the maximum value
is assigned to smallNumber, and it is printed on line 6. On line 9 smallNumber is incremented again, and then its new value, 1, is printed. Wrapping Around a signed IntegerA 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:-32767Analysis: On line 4, smallNumber
is declared this time to be a signed short integer (if you don't
explicitly say that it is unsigned, it is assumed to be signed).
The program proceeds much as the preceding one, but the output is quite different.
To fully understand this output, you must be comfortable with how signed
numbers are represented as bits in a two-byte integer. For details, check Appendix
C, "Binary and Hexadecimal." CharactersCharacter 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.
In the ASCII code, the lowercase letter "a" is assigned the value 97. All the lower- and uppercase letters, all the numerals, and all the punctuation marks are assigned values between 1 and 128. Another 128 marks and symbols are reserved for use by the computer maker, although the IBM extended character set has become something of a standard. Characters and NumbersWhen 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: } Output: !"#$%G'()*+,./0123456789:;<>?@ABCDEFGHIJKLMNOP _QRSTUVWXYZ[\]^'abcdefghijklmnopqrstuvwxyz<|>~sThis simple program prints the character values for the integers 32 through 127. Special Printing CharactersThe C++ compiler recognizes some special characters for formatting. Table 3.2 shows the most common ones. You put these into your code by typing the backslash (called the escape character), followed by the character. Thus, to put a tab character into your code, you would enter a single quotation mark, the slash, the letter t, and then a closing single quotation mark: char tabCharacter = `\t';This example declares a char variable (tabCharacter) and initializes it with the character value \t, which is recognized as a tab. The special printing characters are used when printing either to the screen or to a file or other output device.
Table 3.2. The Escape Characters.
ConstantsLike 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 ConstantsC++ 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 int; 39 is a literal constant. You can't assign a value to 39, and its value can't be changed. Symbolic ConstantsA 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;
In this example, 15 is a literal constant. Your code would be easier to read, and easier to maintain, if you substituted a symbolic constant for this value: students = classes * studentsPerClassIf you later decided to change the number of students in each class, you could do so where you define the constant studentsPerClass without having to make a change every place you used that value. There are two ways to declare a symbolic constant in C++. The old, traditional, and now obsolete way is with a preprocessor directive, #define. Defining Constants with #define To define a constant the traditional way, you would enter this: #define studentsPerClass 15Note that studentsPerClass is of no particular type (int, char, and so on). #define does a simple text substitution. Every time the preprocessor sees the word studentsPerClass, it puts in the text 15. Because the preprocessor runs before the compiler, your compiler never sees your constant; it sees the number 15. Defining Constants with const Although #define works, there is a new, much better way to define constants in C++: const unsigned short int studentsPerClass = 15;This example also declares a symbolic constant named studentsPerClass, but this time studentsPerClass is typed as an unsigned short int. This method has several advantages in making your code easier to maintain and in preventing bugs. The biggest difference is that this constant has a type, and the compiler can enforce that it is used according to its type.
Enumerated ConstantsEnumerated constants enable you to create new types and then to define variables of those types whose values are restricted to a set of possible values. For example, you can declare COLOR to be an enumeration, and you can define that there are five values for COLOR: RED, BLUE, GREEN, WHITE, and BLACK. The syntax for enumerated constants is to write the keyword enum, followed by the type name, an open brace, each of the legal values separated by a comma, and finally a closing brace and a semicolon. Here's an example: enum COLOR { RED, BLUE, GREEN, WHITE, BLACK };This statement performs two tasks:
Every enumerated constant has an integer value. If you don't specify otherwise, the first constant will have the value 0, and the rest will count up from there. Any one of the constants can be initialized with a particular value, however, and those that are not initialized will count upward from the ones before them. Thus, if you write enum Color { RED=100, BLUE, GREEN=500, WHITE, BLACK=700 };then RED will have the value 100; BLUE, the value 101; GREEN, the value 500; WHITE, the value 501; and BLACK, the value 700. You can define variables of type COLOR, but they can be assigned only one of the enumerated values (in this case, RED, BLUE, GREEN, WHITE, or BLACK, or else 100, 101, 500, 501, or 700). You can assign any color value to your COLOR variable. In fact, you can assign any integer value, even if it is not a legal color, although a good compiler will issue a warning if you do. It is important to realize that enumerator variables actually are of type unsigned int, and that the enumerated constants equate to integer variables. It is, however, very convenient to be able to name these values when working with colors, Chapters of the week, or similar sets of values. Listing 3.7 presents a program that uses an enumerated type. Listing 3.7. A demonstration of enumerated constants. 1: #include <iostream.h> 2: int main() 3: { 4: enum Chapters { SunChapter, MonChapter, TuesChapter, WednesChapter, ThursChapter, FriChapter, Â_SaturChapter }; 5: 6: Chapters ChapterOff; 7: int x; 8: 9: cout << "What Chapter would you like off (0-6)? "; 10: cin >> x; 11: ChapterOff = Chapters(x); 12: 13: if (ChapterOff == SunChapter || ChapterOff == SaturChapter) 14: cout << "\nYou're already off on weekends!\n"; 15: else 16: cout << "\nOkay, I'll put in the vacation Chapter.\n"; 17: return 0; 18: } Output: What Chapter would you like off (0-6)? 1 Okay, I'll put in the vacation Chapter. What Chapter would you like off (0-6)? 0 You're already off on weekends!Analysis: On line 4, the enumerated
constant Chapters is defined, with seven values counting upward from 0. The
user is prompted for a Chapter on line 9. The chosen value, a number between 0 and 6,
is compared on line 13 to the enumerated values for SunChapter and SaturChapter, and action
is taken accordingly. You cannot type the word "SunChapter" when prompted for a Chapter; the program does not know how to translate the characters in SunChapter into one of the enumerated values.
SummaryThis 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 (char, short, 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. You must declare a variable before it can be used, and then you must store the type of data that you've declared as correct for that variable. If you put too large a number into an integral variable, it wraps around and produces an incorrect result. This chapter also reviewed literal and symbolic constants, as well as enumerated constants, and showed two ways to declare a symbolic constant: using #define and using the keyword const. Q&A
WorkshopThe Workshop provides quiz questions to help you solidify your understanding of the material covered, and exercises to provide you with experience in using what you've learned. Try to answer the quiz and exercise questions before checking the answers in Appendix D, and make sure that you understand the answers before continuing to the next chapter. Quiz
Exercises
| |
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| | Home | About us | Categories | New Releases | Most Popular | Web tutorial | IT News | Drivers | Submit a program | |
| © 2005 SoftLookup Corp. Privacy Statement |