Bring back foreach int indexes

Walter Bright newshound2 at digitalmars.com
Sun Mar 24 16:33:06 UTC 2024


When size_t is 64 bits, the reason:

     foreach (int i; 0 .. array.length)

gives an error is the same reason that:

     size_t s;
     int i = s;

gives an error. A 64 bit integer cannot be converted to a 32 bit integer without 
risk of losing data.

If the loop is rewritten as:

     foreach (i; 0 .. array.length)

then the problem goes away.

size_t is 64 bits for a machine with 64 bit pointers. This also means that 
registers are 64 bits in size, so no memory and no performance is saved by 
making the index 32 bits. It's the "natural" size for an index.

BTW, there have been endless bugs in C programs when converting them between 
16-32-64 bits, because C doesn't give an error when converting from a larger 
integer type to a smaller one. It just truncates. These bugs tend to be hidden 
and hard to track down. Such overflows are also exploited for malware purposes.

D is doing the right thing and the code is portable between 32<=>64 bits pretty 
much by default. When was the last time you heard of a 32<=>64 bit porting bug 
with D? I don't recall one. Many of D's design decisions came from living 
through the C/C++ conversion bugs by transitioning 16-32-64.

Just use:

     foreach (i; 0 .. array.length)

and let the compiler take care of it for you.


More information about the Digitalmars-d mailing list