foreach problem

BCS nothing at pathlink.com
Fri Jan 5 10:37:02 PST 2007


Frits van Bommel wrote:
> Dejan Lekic wrote:
>> Compiling foreach_bug.d produces an error, while compiling 
>> foreach_ok.d does
>> not. IMHO that is a bug - it is clearly stated in current 
>> specification of The
>> Language 
>> (http://www.digitalmars.com/d/statement.html#ForeachStatement) that
>> variable can be declared outside.
> 
> No it's not. I just reread all of it. I didn't find any mention of that, 
> nor a code sample that would support your case.
> Furthermore, if it _did_ state that somewhere, it'd be a 'bug' in the 
> specification, not in the compiler.
> 

The spec actually asserts the exact opposite (but you really have to 
look carefully to see it).


"At the start of each iteration, the variables _declared_ by the 
ForeachTypeList  are set to be a copy of the elements of the aggregate. 
If the variable is inout, it is a reference to the contents of that 
aggregate."

Based on this (note emphasis) the foreach is always declaring the 
variable. This can only be true if it is a new variable created at that 
point.

OTOH In many cases allowing exactly the usage you are trying for would 
make many things a lot easier. I would like to see it added.


int[] a = ...;
int e;

foreach(e_; a)
{
	if(0 == e_ % 2)
	{
		e = e_
		break;
	}
}

vs.

int[] a = ...;
int e;

foreach(e; a) if(0 == e % 2) break;


To avoid some bugs when doing this unintentionally, maybe require 
something like this:

int[] a = ...;
int e;

foreach(alias e; a) if(0 == e % 2) break;


More information about the Digitalmars-d-bugs mailing list