IElite
IElite

Reputation: 1848

Using Continue in a While loop

Can the Continue be used in a While loop when working with text files?

I would like to do some processing and check some values. If true, i would like to skip a iteration. If false, i would like to continue with the next set of lines (continue processing).

while not EOF(InFile) do  
begin  
 DoSomething;  
 if (AcctTag = '') OR (MasterId = '') then  
  Continue;  
 DoSomething;  
end;  

Does the continue in this case skip a iteration?

Upvotes: 7

Views: 17297

Answers (2)

Rob Kennedy
Rob Kennedy

Reputation: 163357

A test isn't even necessary. The documentation already tells you the answer:

In Delphi code, the Continue procedure causes the flow of control to proceed to the next iteration of the enclosing for, while, or repeat statement.

Notice that there are no caveats about what the loop is doing. The Continue statement proceeds to the next iteration of any loop. In your case, that means Eof will be checked again, and then the body of the loop will run.

Upvotes: 10

Ken White
Ken White

Reputation: 125767

Seems a quick 30-second test would answer that more quickly than a post here. :)

program Project2;

{$APPTYPE CONSOLE}

uses
  SysUtils;

var
  i, j: Integer;

begin
  j := 0;
  i := 0;
  while i < 10 do
  begin
    Inc(i);
    if Odd(i) then
      Continue;
    Inc(j);
    WriteLn(Format('i = %d, j = %d', [i, j]));
  end;
  ReadLn;
end.

Sample output

Note that i is incremented before the call to Continue, which results in j displaying odd numbers, i displaying even? j is only incremented when the loop goes past the Continue test.

A while works the same way whether you're incrementing an integer, concatenating a string, or reading from a text file. A while is a while is a while no matter how you use it. You just need to make sure, in your code above, that DoSomething actually reads the next line from the file or you'll end up in a continuous loop.

Upvotes: 13

Related Questions