Bring back foreach int indexes
Nick Treleaven
nick at geany.org
Mon Mar 25 22:27:10 UTC 2024
On Sunday, 24 March 2024 at 08:23:03 UTC, Liam McGillivray wrote:
> On Thursday, 30 November 2023 at 15:25:52 UTC, Jonathan M Davis
> wrote:
>> Because size_t is uint on 32-bit systems, using int with
>> foreach works just fine aside from the issue of signed vs
>> unsigned (which D doesn't consider to be a narrowing
>> conversion, for better or worse). So, someone could use int
>> with foreach on a 32-bit system and have no problems, but when
>> they move to a 64-bit system, it could become a big problem,
>> because there, size_t is ulong. So, code that worked fine on a
>> 32-bit system could then break on a 64-bit system (assuming
>> that it then starts operating on arrays that are larger than a
>> 32-bit system could handle).
>
> An interesting, not bad point, but I don't think it's enough to
> justify removing this language feature. It's just too unlikely
> of a scenario to be worth removing a feature which improves
> things far more often than not.
It's good to make any integer truncation visible rather than
implicit - that's the main reason. And given that it will be safe
to use a smaller integer type than size_t when the array length
is statically known (after
https://github.com/dlang/dmd/pull/16334), some future people
might expect a specified index type to be verified as able to
hold every index in the array.
> Firstly, how often would it be that a program wouldn't
> explicitly require more array values than `uint` can fit, but
> is still capable of filling the array beyond that in places
> when the maximum array size is enough?
The 64-bit version of the program may be expected to handle more
data than the 32-bit version. That could even be the reason why
it was ported to 64-bit.
...
> Maybe disallow it from functions marked `@safe`,
@safe is for memory-safety, it shouldn't be conflated with other
types of safety.
> But if it's still considered unacceptable to have the
> now-deprecated format shown above be brought back as a language
> feature, I suggest the following as a compromise:
> ```
> foreach (cast uint i, entry; array)
> ```
Possibly a wrapper could be made which asserts that the length
fits:
```d
foreach (i, entry; array.withIndex!uint)
```
More information about the Digitalmars-d
mailing list