简体   繁体   中英

Why loop While with for inside doen't work?

I'm trying to break out of the while loop by changing the auxboolean variable inside the for loop but it doesn't work. The for loop doesn't exit when auxboolean is set to false . Why?

Also, the for loop seems to start with i having value 9 and counts backwards. Why?

auxboolean:= true;
    while auxboolean do
    begin
      for i := 0 to 8  do
      begin
       auxboolean:=false;
      end;
    end;

When debugging you can see that the first value for i is 9 and it then counts down:

调试

在此处输入图像描述

在此处输入图像描述

The condition for the while loop to continue is auxboolean = true .

The check for auxboolean = true is performed only when the code returns to the while statement. What happens to auxboolean inside the loop has no effect before that check.

The condition for the for loop to continue is that the loop control variable i is 0..8.

The check for i happens equally once per loop, but has no effect on the outer while loop. You can use break to exit the for loop.


edit:

The peculiarity with the for loop starting from 9 and counting down is explained in this post

I'm not sure whether this is still the case in recent releases of Delphi. I think it is, but the debugger does not show decreasing counter values.

I think you want to do something like that:

begin
  auxboolean:=true;

  for i := 0 to 8 do
    begin
      Writeln(i);

      auxboolean:=false;

      if not auxboolean then break;
    end;

  Writeln('End of the program...');
  Readln;
end.

You don't have to use the while loop, instead of it see the break statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM