< previous page page_37 next page >

Page 37
LISTING 3.5 DEMONSTRATES ADDING TOO LARGE A NUMBER TO Asigned INTEGER

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
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
Analysis: 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.
The bottom line, however, is that just like an unsigned integer; the signed integer wraps around from its highest positive value to its highest negative value.
Constants.
New Term: Like variables, constants are data storage locations. But variables vary; constants, on the other hand and as you might have guessed, do not vary.
You must initialize a constant when you create it, and you cannot assign a new value later; once a constant is initialized its value is, in a word, constant.
Literal Constants
New Term: 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 int; 39 is a literal constant. You can't assign a value to 39, and its value can't be changed.

 
< previous page page_37 next page >

If you like this book, buy it!