Node:Terminating loops with return, Next:, Previous:Terminating loops with break, Up:Terminating and speeding loops



Terminating loops with return

Suppose that a program is in the middle of a loop (or some nested loops) in a complex function, and suddenly the function finds its answer. This is where the return statement comes in handy. The return command will jump out of any number of loops and pass the value back to the calling function without having to finish the loops or the rest of the function. (See Nested loops, for clarification of the idea of placing one loop inside another.)

Example:

#include <stdio.h>

int main()
{
  printf ("%d\n\n", returner(5, 10));
  printf ("%d\n\n", returner(5, 5000));
  return 0;
}


int returner (int foo, int bar)
{
  while (foo <= 1000)
  {
    if (foo > bar)
    {
      return (foo);
    }

    foo++;
  }

  return foo;
}

The function returner contains a while loop that increments the variable foo and tests it against a value of 1000. However, if at any point the value of foo exceeds the value of the variable bar, the function will exit the loop, immediately returning the value of foo to the calling function. Otherwise, when foo reaches 1000, the function will increment foo one more time and return it to main.

Because of the values it passes to returner, the main function will first print a value of 11, then 1001. Can you see why?