Thread overview
foreach: compiler warning
Jul 30, 2013
Chris
Jul 30, 2013
John Colvin
Jul 30, 2013
bearophile
July 30, 2013
I don't know if this has been raised before. I compiled an old program which has a foreach loop like this:

foreach(i; 0..10) {
  if (condition) {
    i--; // deprecated
  }
}

dmd 2.063 compiled it without giving me any deprecation warning, but the results were screwed up big time in the program. The loop didn't work as expected. ldc2 gave me this hint:

Deprecation: variable modified in foreach body requires ref storage class

So I changed the loop to

foreach(ref i; 0..10) {
  if (condition) {
    i--;
  }
}

and it worked fine in both versions, dmd and ldc2. Mind you, the ldc2 compiled version of the program worked correctly with the deprecated code too. Only the dmd version didn't, although it didn't complain at compile time.

But maybe this is a well known issue, I haven't checked all issues yet.
July 30, 2013
On Tuesday, 30 July 2013 at 14:27:18 UTC, Chris wrote:
> I don't know if this has been raised before. I compiled an old program which has a foreach loop like this:
>
> foreach(i; 0..10) {
>   if (condition) {
>     i--; // deprecated
>   }
> }
>
> dmd 2.063 compiled it without giving me any deprecation warning, but the results were screwed up big time in the program. The loop didn't work as expected. ldc2 gave me this hint:
>
> Deprecation: variable modified in foreach body requires ref storage class
>
> So I changed the loop to
>
> foreach(ref i; 0..10) {
>   if (condition) {
>     i--;
>   }
> }
>
> and it worked fine in both versions, dmd and ldc2. Mind you, the ldc2 compiled version of the program worked correctly with the deprecated code too. Only the dmd version didn't, although it didn't complain at compile time.
>
> But maybe this is a well known issue, I haven't checked all issues yet.

This has been discussed recently on the forums, can't remember where. The ldc hint is correct IIRC
July 30, 2013
Chris:

> But maybe this is a well known issue, I haven't checked all issues yet.

Take a look at Bugzilla, and if you don't find this missed warning, then I suggest to file it.

Bye,
bearophile