HPlogo HP C/HP-UX Reference Manual: Version A.05.55.02 > Chapter 4 Type Conversions

Integral Promotions

» 

Technical documentation

Complete book in PDF

 » Table of Contents

 » Index

Wherever an int or an unsigned int may be used in an expression, a narrower integral type may 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/HP-UX, 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, compatibility 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 compatibility mode. The following program shows two expressions that are evaluated differently in the two modes.

   #include <stdio.h>
   main ()
   {
      unsigned short us = 1;
      printf ("Quotient = %d\n",-us/2);
      printf ("Comparison = %d\n",us<-1);
   }

In compatibility mode, as with many pre-ANSI compilers, the results are:

Quotient   = 2147483647
Comparison = 1

ANSI C gives the following results:

Quotient   = 0
Comparison = 0

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. See Chapter 9 “Compiling and Running HP C Programs ” for information on enabling ANSI migration warnings.

© Hewlett-Packard Development Company, L.P.