Foreach loop behaviour and manipulation

Binarydepth binarydepth at gmail.com
Thu Nov 28 16:32:01 PST 2013


On Thursday, 28 November 2013 at 23:45:26 UTC, H. S. Teoh wrote:
> 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

Thank you for you response! That's exactly what I was thinking.  
It can be really chaotic to make that mistake in a for loop. But 
it can be fixed with a temporary variable and reset the value of 
the counter at the end of the execution of the loop just before 
it gets incremented.

Here is the C version of this program. I made a mistake the first 
time I made this version. I left the function as an INT function 
and didn't return any value.

On the D version the compiler warned me about that which makes a 
lot of sense. I liked that! :D .

S I went and fixed both codes but the D compiler is not doing a 
good compilation and i get segmentation fault when I run the D 
version.

Finally here's the C code that gives the correct output :
----------------------------------------------------------------------------
#include <stdio.h>
void funcion(int a, int t)
{
int temp, bd, an;
temp=t;
	temp*=20;
	temp+=402;
	temp*=5;
	temp+=3;
bd=temp-a;
temp=t;
	temp*=5;
	temp+=50;
	temp*=20;
	temp+=1013;
an=temp-a;
printf("%d:%d\n", bd, an);
}
void main()
{
int r, f, count, b;
printf("Input your birth year : ");
scanf("%d", &b);
printf("Input the range of sizes for the calculation (# #) : ");
scanf("%d %d", &r, &f);
for(count=r; count<=f; count++)
	{
		funcion(b, count);
	}
}
--------------------------------------------------------------


More information about the Digitalmars-d-learn mailing list