The Middle Ground

C doesn't provide a mid-test loop like the one we discussed at the beginning of this part. But it does give us the machinery to build our own. If we use the while and break statements and the fact that the number 1 is considered true in conditional expressions, we can create a mid-test look in this way:

while( 1 ) {
   Block 1
   if( condition )
      break ;
   Block 2

This may not seem quite what you were expecting. After all we haven't seen the break used with a loop, only with the switch. A break in a loop works much like it does in a switch, it jumps out of the statement. Here the break will jump to the closing brace for the while where we'll pick up the flow of control with the statement that follows that brace.

There's another important thing to notice about this loop. Here the condition does not tell under what circumstances to continue, but instead it tell us when to leave the loop. That's a bit different from the other loops.

An Example

Let's return to an example we had when looking at the do-while statement earlier. There we asked the user to input a number and repeated if they did it out of range. However, we didn't print out an error message if it was and we repeated. We can do so most naturally with a mid-test loop:

while( 1 ) {
   printf( "Enter a number: " ) ;
   scanf( "%d", &x ) ;
   if( x >= 0 && x <= 100 )
      break ;
   printf( "The number should be between 0 and 100 (inclusive).\n" ) ;

If we tried to do the same thing using only the while, do-while or for statements (without the break), we'd find that we either had to introduce extra variables or repeat some of the code. Usually the simpler solutions are preferable since they are (hopefully) less error-prone.

You probably won't see or use mid-test loops as often as while and for loops. Personally, however, I have found that increasingly I am recognizing programming structures as mid-test loops and implementing them like this. It is becoming a very useful abstraction.

What will x and y equal after this code is executed?
x = 3 ;
while( 1 ) {
   y = 2 * x ;
   if( y > x + 4 )
      break ;
   x++ ;

3, 3
3, 6
5, 10
6, 10
3, 8