break Statement

The "break" statement has two uses. The first has already been described in conjunction with the "switch" statement. A "break" statement that is enclosed deepest by a "switch" statement, will cause the control flow to jump to the first statement after the closing curly brace, '{', of the "switch" statement.,/p>

The "break" statement has a similar meaning if the deepest or innermost statement that contains it is a: "while", "do", or "for" statement. In this context, a "break" statement will cause the control flow to jump to the first statement after the loop."

Thus, the following program fragment:

	for(e1;e2;e3) {
		...
		if (e4) break;
		...
	}
	s;

will cause statement 's' to be executed when the "break" statement in the "if" within the "for" loop is executed (i.e. when e4 is true).

This is equivalent to the following use of a "goto" statement:

	for(e1;e2;e3) {
		...
		if (e4) goto done;
		...
	}
	done:
	s;

but is simpler and clearer since it is not necessary to search for the label (which could be anywhere in the function).

If one loop statement ("while" or "do" or "for") is enclosed by another; and a "break" appears within the inner loop, then control flow will come out of the inner loop but still be within the outer loop.

If there is no statement after the closing curly brace, e.g.

	function() { int x;
		...
		while(x) {
			...
			if(x==7) break;
		}
	}

then the invisible "return" statement at the end of the function is executed. Note that the compile may object because the function does not return a value of type int, as implied.


© 1991-2008 Prem Sobel. All Rights Reserved.