HP C/iX Reference Manual (31506-90011)
50 Chapter4
Type Conversions
Integral Promotions
Integral Promotions
Wherever an int or an unsigned int can be used in an expression, a narrower integral type
can also be used. The narrow type will generally be widened by means of a conversion
called an integral promotion. All ANSI C compilers follow what are called value preserving
rules for the conversion. In HP C the value preserving integral promotion takes place as
follows: a char, a short int, a bit-field, or their signed or unsigned varieties, are widened to
an int; all other arithmetic types are unchanged by the integral promotion.
NOTE
Many older compilers, including previous releases of HP C, performed
integral promotions in a slightly different way, following unsigned preserving
rules. In order to avoid "breaking" programs that may rely on this non-ANSI
behavior, non-ANSI mode continues to follow the unsigned preserving rules.
Under these rules, the only difference is that unsigned char and unsigned
short are promoted to unsigned int, rather than int.
In the vast majority of cases, results are the same. However, if the promoted result is used
in a context where its sign is significant (such as a division or comparison operation),
results can be different between ANSI mode and non-ANSI mode. The following program
shows two expressions that are evaluated differently in the two modes.
#include
main ()
{
unsigned short us = 1;
printf ("Quotient = %d\n",-us/2);
printf ("Comparison = %d\n",us<-1);
}
To avoid situations where unsigned preserving and value preserving promotion rules yield
different results, you could refrain from using an unsigned char or unsigned short in an
expression that is used as an operand of one of the following operators: >>, /, %, <, <=, >, or
>=. Or remove the ambiguity by using an explicit cast to specify the conversion you want.
If you enable ANSI migration warnings, the compiler will warn you of situations where
differences in the promotion rules might cause different results.
In non-ANSI mode, as with many pre-ANSI compilers, the results will be:
Quotient = 2147483647
Comparison = 1
ANSI C gives the following results:
Quotient = 0
Comparison = 0