[OT] The Usual Arithmetic Confusions

Walter Bright newshound2 at digitalmars.com
Fri Feb 4 21:13:10 UTC 2022


On 2/4/2022 6:01 AM, Paul Backus wrote:
>> Trying to hide the reality of how computer integer arithmetic works, and how 
>> integral promotions work, is a prescription for endless frustration and 
>> inevitable failure.
> 2s-complement is "the reality of how computer integer arithmetic works," but 
> there is nothing fundamental or necessary about C's integer promotion rules, and 
> plenty of system-level languages get by without them.

The integral promotion rules came about because of how the PDP-11 instruction 
set worked, as C was developed on an -11. But this has carried over into modern 
CPUs. Consider:

void tests(short* a, short* b, short* c) { *c = *a * *b; }
         0F B7 07                movzx   EAX,word ptr [RDI]
66      0F AF 06                imul    AX,[RSI]
66      89 02                   mov     [RDX],AX
         C3                      ret

void testi(int* a, int* b, int* c) { *c = *a * *b; }
         8B 07                   mov     EAX,[RDI]
         0F AF 06                imul    EAX,[RSI]
         89 02                   mov     [RDX],EAX
         C3                      ret

You're paying a 3 size byte penalty for using short arithmetic rather than int 
arithmetic. It's slower, too.

Generally speaking, int should be used for most calculations, short and byte for 
storage.

(Modern CPUs have long been deliberately optimized and tuned for C semantics.)


More information about the Digitalmars-d mailing list