Download

Breaking out early

Suppose that a program is in the middle of some awkward process in afunction which is not main(), perhaps two or three loops working together,for example, and suddenly the function finds its answer. This is where thebeauty of the return statement becomes clear. The program can simply callreturn(value) anywhere in the function and control will jump out of anynumber of loops or whatever and pass the value back to the calling statementwithout having to finish the function up to the closing brace }.myfunction (a,b) /* breaking out of functions early */int a,b;{while (a < b){if (a > b){return (b);}a = a + 1;}}

The example shows this. The function is entered with some values for a andb and, assuming that a is less than b, it starts to execute one of C’s loopscalled while. In that loop, is a single if statement and a statement whichincreases a by one on each loop. If a becomes bigger than b at any pointthe return(b) statement gets executed and the function myfunction quits,without having to arrive at the end brace ‘}’, and passes the value of b backto the place it was called.