OT (partially): about promotion of integers

eles eles at eles.com
Tue Dec 11 07:20:51 PST 2012


Hello,

  The previous thread, about the int resulting from operations on 
bytes, rised me a question, that is somewhat linked to a 
difference between Pascal/Delphi/FPC (please, no flame here) and 
C/D.

  Basically, as far as i get it, both FPC and C use Integer (name 
it int, if you like), as a fundamental type. That means, among 
others, that this is the prefered type to cast (implicitely) to.

  Now, there is a difference between the int-FPC and the int-C: 
int-FPC is the *widest* integer type (and it is signed), and all 
others integral types are subranges of this int-FPC. That is, the 
unsigned type is simply a sub-range of positive numbers, the char 
type is simply the subrange between -128 and +127 and so on.

  This looks to me as a great advantage, since implicit 
conversions are always straightforward and simple: everything is 
first converted to the fundamental (widest) type, calculation is 
made (yes, there might be some optimizations made, but this 
should be handled by the compiler, not by the programmer), then 
the final result is obtanied.

  Note that this approach, of making unsigned integrals a subrange 
of the int-FPC halves the maximum-representable number as 
unsigned, since 1 bit is always reserved for the sign (albeit, 
for unsigned, it is always 0).

  OTOH, the fact that the int-FPC is the widest available, makes 
it very naturally as a fundamental type and justifies (I think, 
without doubt), the casting all other types to this type and of 
the result of the arithmetic operation. If this result is in a 
subrange, then it might get casted back to a subrange (that is, 
another integral type).

  In C/D, the problem is that int-C is the fundamental (and 
prefered for conversion) type, but it is not the widest. So, you 
have a plethora of implicit promotions.

  Now, the off-topic question: the loss in unsigned-range aside 
(that I find it to be a small price for the earned clarity), is 
that any other reason (except C-compatibility) that D would not 
implement that model (this is not a suggestion to do it now, I 
know D is almost ready for prime-time, but it is a question), 
that is the int-FPC like model for integral types?

Thank you,

  Eles


More information about the Digitalmars-d mailing list