Deprecation: foreach: loop index implicitly converted from size_t to int
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Fri Jan 18 19:02:02 UTC 2019
On Friday, January 18, 2019 8:34:22 AM MST Michael via Digitalmars-d-learn
wrote:
> On Friday, 18 January 2019 at 13:29:29 UTC, Adam D. Ruppe wrote:
> > On Friday, 18 January 2019 at 12:27:17 UTC, Michael wrote:
> >> This, to be, looks like quite the explicit conversion, no?
> >
> > Yeah, I agree. But the language is silly. I just leave the type
> > out of foreach and explicitly cast it inside the body.
>
> Thank you all for the concise explanations and suggestions, I
> think that's fairly straightforward. I thought perhaps I was
> doing the sensible thing of dealing with the conversion inside
> the foreach statement, but I guess not!
Well, you were really doing the equivalent of simply declaring a variable
without a cast. e.g.
int i = arr.length;
rather than
int i = cast(int)arr.length;
In general, if the compiler treated giving the foreach variable an explicit
type as being a cast, it would make it really easy to screw up and
unknowingly give a different type than the actual type of the values and end
up with an invisible cast, which could cause subtle bugs.
IIRC, the only case where foreach treats giving an explict type as anything
like a cast is when you're iterating over a string type, and you give a
character type different from the character type of the string. In that
case, it actually decodes the string from one Unicode encoding and encodes
it in the other. Whether the language should have done that rather than
requiring that a library solution be used is debatable (I believe that it
far predates Phobos having the Unicode handling that it does now), but at
least it can't result in stuff like silent truncation. Worst case, it has a
silent performance hit, or you get an unexpected UnicodeException at runtime
due to invalid Unicode.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list