Deprecation: foreach: loop index implicitly converted from size_t to int

Steven Schveighoffer schveiguy at gmail.com
Fri Jan 18 13:17:53 UTC 2019


On 1/18/19 7:27 AM, Michael wrote:
> Hello all,
> 
> I am getting this deprecation warning when compiling using DMD64 D 
> Compiler v2.084.0 on Linux. I'm a little unsure what the problem is, 
> however, because the code producing these warnings tends to be of the form:
> 
>> foreach (int i, ref prop; props)
> 
> This, to be, looks like quite the explicit conversion, no? Does it mean 
> I now have to use to!int(i) to convert the type of i in a foreach now?

That's one possibility.

You can avoid to!int by using a mask or a cast:

foreach(_i, ref prop; props)
{
    int i = _i & 0xffff_ffff;
    auto i2 = cast(int)_i;
}

It's less than ideal, but the reason is that there is a possibility that 
props could have 2^31 or more elements, in which case int will not cut 
it. It's forcing you to make that decision that it's OK vs. the compiler 
making that assumption. Any time the compiler is throwing away data 
without a cast, D tends to require buy in from the developer.

Note that this is much more of a problem with smaller types (short or 
byte), but it would be inconsistent not to also flag int as problematic.

I would recommend just using foreach(i, ref prop; props) and casting 
only where it's absolutely necessary.

-Steve


More information about the Digitalmars-d-learn mailing list