This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
So a plain break in the switch statement causes the switch statement ONLY to break out, right? Then how am I to think of the labeling? When you apply a label, is it like you are giving the loop an identifier and saying "break label" means break out of that loop, and "continue label" means move to conditional check for that loop? [ June 10, 2003: Message edited by: Brian Joseph ]
The simplest explanation I can give is that a break or continue statement will cause the enclosing context to terminate abruptly. That means that, if the break or continue statement is found within a for loop, it causes that for loop to terminate, if it's found within a switch statement, the switch statement terminates. Of course, there is a slight difference between the two. Break causes the enclosing context to terminate abruptly and execution continues after that context. Continue, on the other hand, causes the enclosing context to terminate the current loop and continues in the next iteration of the enclosing context. (Note that continue statements are generally only used in loops, switch statements will almost always use a break statement.) Ok, so what about labelled breaks and continues. Let's take a look at this example code:
What would be the output from uncommenting lines 1 through 6? Let's look at a couple of them. If we use line 1, we have an unlabelled break statement. That means that the immediately enclosing context will terminate abruptly. What's the immediate closing context? That would be the inner loop that uses j as a counter. In order to find the immediately enclosing context, just trace back until you find a loop or switch statement in the code. Therefore, usign this line produces output like this:
What happens if we use line 2 instead of line 1? Well, now we terminate the context with the matching label. In this case, the context with the matching label is the inner loop, which is also the immediate enclosing context. Therefore, line 2 produces the same output as line 1. How about line 3? Now, we abruptly halt the matching context, but that context is the outer loop, rather than the inner loop. Therefore, we get this output:
Try out the continue statements on your own and, if you have more questions, please let me know. I hope that helps, Corey