Expert C Programming

(Jeff_L) #1

Every char in an expression is converted into an int....Notice that all float's in an expression are
converted to double....Since a function argument is an expression, type conversions also take place
when arguments are passed to functions: in particular, char and short become int, float
becomes double.


—The C Programming Language, first edition


The feature is known as type promotion. When it happens to integer types it's called "integral
promotion". The concept of automatic type promotion carried over to ANSI C, although it was
watered down in places. The ANSI C standard has this to say about it:


In executing the fragment


char c1, c2;


/ ... /


c1 = c1 + c2;


the "integral promotions" require that the abstract machine promote the value of each variable to int
size and then add the two ints and truncate the sum. Provided the addition of two chars can be done
without creating an overflow exception, the actual execution need only produce the same result,
possibly omitting the promotions.


Similarly, in the fragment


float f1, f2;


double d;


/ ... /


f1=f2*d;


the multiplication may be executed using single-precision arithmetic if the implementation can
ascertain that the result would be the same as if it were executed using double-precision arithmetic
(for example, if d were replaced by the constant 2.0, which has type double).


—ANSI C Standard, Section 5.1.2.3


Table 8-1 provides a list of all the usual type promotions. These occur in every expression, not just in
expressions involving operators and mixed-type operands.


Table 8-1. Type Promotions in C
Original Type Usually Promoted To
char int
bit-field int
enum int
unsigned char int
short int
unsigned short int
Free download pdf