Foreach loop behaviour and manipulation

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Nov 28 15:43:57 PST 2013


On Fri, Nov 29, 2013 at 12:36:18AM +0100, Binarydepth wrote:
> Hi guys I'm having some problems. Calculations are not working as
> expected and I get segmentation fault. I used the 2.059 version and
> it runs after compilation on compileonline.com
[...]
> foreach(t; 1..51)
>     {
> 	temp=t;
> 	t*=20;

Modifying the loop variable of a foreach is, in general, a risky move.
If you need to make loop indices jump around, you should use a plain for
loop instead:

	for (t=1; t < 51; t++)
	{
		// modify t at will, just make sure your loop
		// condition(s) / loop increments still work correctly.
	}

or, if the loop indices are truly wildly jumping around, use a while
loop:

	t = 1;
	while (t < 51 /* or whatever condition you may have */)
	{
		... // Do stuff
		t = ... // compute next index to jump to
	}


T

-- 
The computer is only a tool. Unfortunately, so is the user. -- Armaphine, K5


More information about the Digitalmars-d-learn mailing list