foreach(ubyte j;0 .. num) is bugging out

Ruby The Roobster michaeleverestc79 at gmail.com
Thu Sep 23 00:30:45 UTC 2021


On Thursday, 23 September 2021 at 00:17:49 UTC, jfondren wrote:
> On Thursday, 23 September 2021 at 00:06:42 UTC, Ruby The 
> Roobster wrote:
>> So, I have the following function:
>> ```d
>> 	        writeln(tempcolor); //For this matter, the program 
>> correctly reports tempcolor as 1...
>> 		for(ubyte j = 0;j < tempcolor; j++ /*trying ++j has same 
>> effect*/ )	{ //tempcolor is 1, yet this sloop gets executed 
>> twice...
>> 			writeln();
>> 			posfunc(ftext, main, exp, temp, i, j, points , x);          
>>                               //Orignally foreach loop, but 
>> switching to for loop has same effect...
>> 		}
>> ```
>
> Needs more print in your print debugging:
>
> ```d
> writeln("tempcolor: ", tempcolor);
> ...
> writeln("in tempcolor with j: ", j);
> ```
>
> output:
>
> ```
> tempcolor: 1
> in tempcolor with j: 0
> ...
> ... numbers
> ...
> tempcolor: 0
> tempcolor: 0
> tempcolor: 0
> tempcolor: 0
> tempcolor: 0
> tempcolor: 0
> tempcolor: 0
> tempcolor: 0
> tempcolor: 0
> tempcolor: 1
> in tempcolor with j: 0
>```


I figured out something weird. The variable 'i' is passed by 
reference, yet the variable 'i' of the loop isn't being 
incremented by posfunc.  I assume foreach creates a new i 
variable at the start of each new loop. Swapping the original 
loop with a while loop fixes the problem.  Thank you very much 
for trying to help.



More information about the Digitalmars-d-learn mailing list