Sams Teach Yourself C in 21 Days

(singke) #1
Working with Memory 567

20


the compiler would first use the operand,Xand the operand 2. Once in completes it
would use the resulting value and the operand Y.
Within expressions, individual operands are promoted as necessary to match the associ-
ated operands in the expression. Operands are promoted, in pairs, for each binary opera-
tor in the expression. Of course, promotion isn’t needed if both operands are the same
type. If they aren’t, promotion follows these rules:


  • If either operand is a long double, the other operand is promoted to type long
    double.

  • If either operand is a double, the other operand is promoted to type double.

  • If either operand is a float, the other operand is promoted to type float.

  • If either operand is a long, the other operand is converted to type long.
    For example, if xis an intandyis a float, evaluating the expression x/ycausesxto be
    promoted to type floatbefore the expression is evaluated. This doesn’t mean that the
    type of variable xis changed. It means that a type floatcopy of xis created and used in
    the expression evaluation. The value of the expression is, as you just learned, type float.
    Likewise, if xis a type doubleandyis a type float,ywill be promoted to double.


Conversion by Assignment
Promotions also occur with the assignment operator. The expression on the right side of
an assignment statement is always promoted to the type of the data object on the left side
of the assignment operator. Note that this might cause a “demotion” rather than a promo-
tion. If fis a type floatandiis a type int,iis promoted to type floatin this assign-
ment statement:
f = i;
In contrast, the assignment statement
i = f;
causesfto be demoted to type int. Its fractional part is lost on assignment to i.
Remember that fitself isn’t changed at all; promotion affects only a copy of the value.
Thus, after the following statements are executed
float f = 1.23;
int i;
i = f;
the variable ihas the value 1 , andfstill has the value 1.23. As this example illustrates,
the fractional part is lost when a floating-point number is converted to an integer type.

32 448201x-CH20 8/13/02 11:16 AM Page 567

Free download pdf