2.3.5.5 break and continue.

In C and C++ we have two useful statements break and continue which may be used to add fine control to loops. Consider the following C code:

while (expression) 
{
   if (expression1) 
   {
      continue;
   }
   if (expression2) 
   {
      break;
   }
}

The code above shows how break and continue are used. Firstly you have a loop which takes an expression to determine general termination procedure. Now let us assume that during execution of the loop you decide that you have completed what you wanted to do and may leave the loop early, the break forces a 'jump' to the next statement after the end of the loop. A continue is similar but it takes you to the top of the loop.

In Ada there is no continue, and break is now called exit.

while expression loop
   if expression2 then
      exit;
   end if;
end loop;

The Ada exit statement however can combine the expression used to decide that it is required, and so the code below is often found.

while expression loop
   exit when expression2;
end loop;

This leads us onto the do loop, which can now be coded as:

loop
   statements
   exit when expression;
end loop;

The problem with the break statement comes when used in complex code with nested loops.

Example 2.2 - Control of nested loops.

The following example code is quite common in style, an inner loop spots the termination condition and has to signal this back to the outer loop. C has no way to use the break statement to exit from an inner loop.

{
   int percent_found = 0;

   fgets(file_handle, buffer);

   while ((!feof(file_handle) && (!percent_found)) 
   {
      for (char_index = 0; 
           buffer[char_index] != '\n';
           char_index++) 
      {
         if (buffer[char_index] == '%') 
         {
            percent_found = 1;
            break;
         }
         // some other code, including get next line.
      }

      fgets(file_handle, buffer);

   }
}

Now consider the example below in Ada (note that in both examples code before and after has been omitted for clarity, the Ada example below is more complete in the accompanying source).

Example - Complex_Loops.adb

As you can see we have now used the loop name Main_Loop with the nested exit statement to allow us to break out of the inner loop. This level of control, without the use of additional boolean flags, can minimise the complexity of nested loop management and increase the ease with which it is read, understood and maintained.


Previous PageContents PageNext Page

Copyright © 1996 Simon Johnston &
Addison Wesley Longman