< previous page page_549 next page >

Page 549
character data, there is no problem. C++ guarantees that each character in a machine's character set (such as ASCII) is a nonnegative value. Using character data, promotion from char to int gives the same result on any machine with any compiler.
But if you try to save memory by using the char type for manipulating small signed integers, then promotion of these values to the int type can produce different results on different machines! That is, one machine may promote negative char values to negative int values, whereas the same program on another machine might promote negative char values to positive int values. The moral is this: Unless you are squeezed to the limit for memory space, do not use char to manipulate small signed numbers. Use char only to store character data.
Type Coercion in Assignments, Parameter Passage, and Return of a Function Value
In general, promotion of a value from one type to another does not cause loss of information. Think of promotion as moving your baseball cards from a small shoe box to a larger shoe box. All of the cards still fit into the new box and there is room to spare. On the other hand, demotion (or narrowing) of data values can potentially cause loss of information. Demotion is like moving a shoe box full of baseball cards into a smaller boxsomething has to be thrown out.
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif 3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
Demotion (Narrowing) The conversion of a value from a higher type to a lower type according to a programming language's precedence of data types. Demotion may cause loss of information.
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
Consider an assignment operation
v = e
where v is a variable and e is an expression. Regarding the data types of v and e, there are three possibilities:
1. If the types of v and e are the same, no type coercion is necessary.
2. If the type of v is higher than that of e (using the type precedence we explained with promotion), then the value of e is promoted to v's type before being stored into v.
3. If the type of v is lower than that of e, the value of e is demoted to v's type before being stored into v.
Demotion, which you can think of as shrinking a value, may cause loss of information:

 
< previous page page_549 next page >