Promotion of integral types

Ray Butterworth rbutterworth at watmath.UUCP
Sat Sep 27 04:27:47 AEST 1986


> It is interesting to note that K&R does not say that unsigned char or
> unsigned short get promoted to unsigned int; it says that they get promoted
> to integer (on page 183), which is a bit vague.  Harbison & Steele says
> very clearly what is said above.  The ANSI Draft (1986.07.09 version) says
> very clearly that unsigned char and unsigned short are promoted to int,
> since the values can all be represented in an int (assuming sizeof(int)
> is greater than sizeof(short), which is usually true).
> 
> What to do?  Frankly, I prefer the ANSI approach, but it does represent a
> silent change from what H&S (and Chris Torek) perceive to be standard
> practice.  For some reason, it is not flagged as such in the rationale
> document; it isn't even discussed there.

There is one major problem with the ANSI proposal.

When doing comparisions, if the two types aren't identical after
the usual conversions and one of them is unsigned, the comparison
is done as unsigned.  e.g. "(-1) >= ui" for all unsigned ints ui.
(In particular, "(-1)>sizeof(anything)" is always true if size_t is
unsigned long or unsigned int.)

This can be somewhat surprising, but one can learn to live with it
once the principle is understood.  The real problem occurs with
shorts and unsigned shorts.  Consider the comparison "neg1>=us",
where "neg1" is an int with value -1 and "us" is any unsigned short.
If sizeof(unsigned short)<sizeof(int), the "us" is promoted to
an int and the comparison is done between ints and the result is
always false.  But if sizeof(unsigned short)==sizeof(int), "us"
is promoted to unsigned int, "neg1" is converted to unsigned int,
and the comparison is always true.

Now this is not only surprising, it means that comparing an
unsigned short with an int (or a constant) can give different
results depending upon the machine one is using.  How many
people are going to keep this in mind while writing their code?



More information about the Comp.lang.c mailing list