Return to Topic Menu | Computer Science Main Page | MathBits.com | Terms of Use | Resource CD

 

Ending a Program or Loop Early

On occasion, it may be necessary to end a program (or section of a program) earlier than its normal termination.  Below are examples of methods of interrupting or terminating programs or loops.

 

 

return 0;

-  it is possible to end a program (or function) prior to its normal termination by using an "extra" return 0; statement.  The drawback to this strategy is that it ends the entire program (or function) at the point where the return 0; statement is placed.  This may not always be what you had in mind.  Oftentimes, the programmer may wish to simply end a "process" within the program, but continue with the remainder of the programming code.

return 0; returns a value of 0 to the IDE indicating that the program reached normal termination.

 

exit( );

- the exit( ) function also ends a program before its normal termination.  It requires the Standard Library header file, stdlib.h.  The format is
                                         exit(value);  
where value is an integer variable or value. 

Using exit(1); returns a value of 1 to the IDE indicating that an error must have occurred.  This process is often used for error trapping.

 

break;

- the break statement gets you out of a loop.  No matter what the loop's ending condition, break immediately says "I'm outta here!"  The program continues with the next statement immediately following the loop.  Break stops only the loop in which it resides.  It does not break out of a "nested loop" (a loop within a loop).

 

continue;

- continue performs a "jump" to the next test condition in a loop.  The test condition is then evaluated as usual, and the loop is executed as long as the test condition remains true.  The continue statement may be used ONLY in iteration statements (loops).  It serves to bypass, or jump over, certain iteration sections of a loop.

 

 Return to Topic Menu | Computer Science Main Page | MathBits.com | Terms of Use | Resource CD