foreach counter now must be size_t ?

Nicholas Wilson iamthewilsonator at hotmail.com
Wed Feb 13 02:13:50 UTC 2019


On Wednesday, 13 February 2019 at 01:54:35 UTC, Rubn wrote:
> On Saturday, 9 February 2019 at 02:13:13 UTC, Jonathan M Davis
>> It's not a compiler bug, but the code is still buggy. Using 
>> int for indexing is wrong in the general case. It works for 
>> smaller arrays, but it's just a bug waiting to happen. I see 
>> no problem with the deprecation. Quite the opposite. Using int 
>> when size_t should be used is an incredibly common bug, and 
>> this helps combat that.
>>
>> - Jonathan M Davis
>
> It's a bandaid, the larger problem is allowing the comparison 
> between
> int and size_t. Which my bet is how it is implemented 
> internally, which is why foreach_reverse doesn't work cause it 
> actually has to assign the counter a size_t.
>
> The point was, if you don't see the for() being an issue that 
> has to be fixed. Then there's no reason to see foreach() as an 
> issue to fix. You either fix them both or don't, it doesn't 
> make sense to fix one but not the other. foreach()'s 
> implementation is literally just a for() statement which is 
> where the bug originates from.

The `for` is an issue, but one that is much harder to reason 
about. With `foreach` over arrays, the index is going to be used 
for indexing. With for, the counter (if any) is assigned 
separately and _may_ be used in an arbitrary stopping condition 
and the indexing (if any) is in the loop.


More information about the Digitalmars-d mailing list