break and continue

There are three types of loop structures (for, while, and do statements). They provide structured solutions to most of the repetitive computing tasks. However, the lack of the goto statement makes it not easy to stop a loop in the middle. The break and continue statements can somehow remedy this.

The break statement breaks out of the innermost enclosing for, while, or do loop and continues after the loop. For example, the following code repeatedly reads a command, and executes the command until the command is "quit", in which case the loop will be terminated.

while 1
   command = readline();
   if command == "quit"
        break;
   end
   execute_command(command);
end

The continue statement skips the rest of the current round of the loop and continues with the next iteration.

continue statement is very similar to break statement. The difference is it doesn't break out of the loop altogether, but only breaks out of the current round of the loop. Then the interpreter continues to execute the next iteration in the loop.

In the case of a for loop, the loop counter is updated immediately and its value is tested to determine if a new iteration of loop is to be carried out.

For a while or until loop, the execution flow jumps up to the beginning of the loop body. For a do-while or do-until loop, the rest of the commands of the loop body are skipped and execution flow jumps to the loop condition testing.

For example, the following code repeatedly reads and processes a command. If the command is empty, the loop starts over, if the command is "quit" the loop will be terminated. Otherwise the command is executed and new command is read again.

while 1
   command = readline();
   if command == ""
        continue;
   end
   if command == "quit"
        break;
   end
   execute_command(command);
end
Because of the use of continue, no empty string will be submitted for execution.

oz 2009-12-22