Break out of a while loop that contains a switch statement
I find this form to be ever-so-slightly more readable:
bool done = false;
while (!done)
{
switch (MLTWatcherTCPIP.Get().ToUpper())
{
case "": //scroll/display next inventory location
MLTWatcherTCPIP.TerminalPrompt.ScrollBodyTextDown();
break;
case "P": //scroll/display previous inventory location
MLTWatcherTCPIP.TerminalPrompt.ScrollBodyTextDown();
break;
case "D": //DONE (exit out of this Do Loop)
done = true;
break;
case "Q": //QUIT (exit out to main menu)
return;
default:
break;
}
}
trying to break a while loop with a switch case inside switch case
Try replacing while(true)
with while(!shouldBreak)
as a break
statement only breaks out of the inner-most loop / switch / while etc.
For more details see e.g. Difference between break and continue statement
How to break out of a loop from inside a switch?
Premise
The following code should be considered bad form, regardless of language or desired functionality:
while( true ) {
}
Supporting Arguments
The while( true )
loop is poor form because it:
- Breaks the implied contract of a while loop.
- The while loop declaration should explicitly state the only exit condition.
- Implies that it loops forever.
- Code within the loop must be read to understand the terminating clause.
- Loops that repeat forever prevent the user from terminating the program from within the program.
- Is inefficient.
- There are multiple loop termination conditions, including checking for "true".
- Is prone to bugs.
- Cannot easily determine where to put code that will always execute for each iteration.
- Leads to unnecessarily complex code.
- Automatic source code analysis.
- To find bugs, program complexity analysis, security checks, or automatically derive any other source code behaviour without code execution, specifying the initial breaking condition(s) allows algorithms to determine useful invariants, thereby improving automatic source code analysis metrics.
- Infinite loops.
- If everyone always uses
while(true)
for loops that are not infinite, we lose the ability to concisely communicate when loops actually have no terminating condition. (Arguably, this has already happened, so the point is moot.)
- If everyone always uses
Alternative to "Go To"
The following code is better form:
while( isValidState() ) {
execute();
}
bool isValidState() {
return msg->state != DONE;
}
Advantages
No flag. No goto
. No exception. Easy to change. Easy to read. Easy to fix. Additionally the code:
- Isolates the knowledge of the loop's workload from the loop itself.
- Allows someone maintaining the code to easily extend the functionality.
- Allows multiple terminating conditions to be assigned in one place.
- Separates the terminating clause from the code to execute.
- Is safer for Nuclear Power plants. ;-)
The second point is important. Without knowing how the code works, if someone asked me to make the main loop let other threads (or processes) have some CPU time, two solutions come to mind:
Option #1
Readily insert the pause:
while( isValidState() ) {
execute();
sleep();
}
Option #2
Override execute:
void execute() {
super->execute();
sleep();
}
This code is simpler (thus easier to read) than a loop with an embedded switch
. The isValidState
method should only determine if the loop should continue. The workhorse of the method should be abstracted into the execute
method, which allows subclasses to override the default behaviour (a difficult task using an embedded switch
and goto
).
Python Example
Contrast the following answer (to a Python question) that was posted on StackOverflow:
- Loop forever.
- Ask the user to input their choice.
- If the user's input is 'restart', continue looping forever.
- Otherwise, stop looping forever.
- End.
while True:
choice = raw_input('What do you want? ')
if choice == 'restart':
continue
else:
break
print 'Break!'
Versus:
- Initialize the user's choice.
- Loop while the user's choice is the word 'restart'.
- Ask the user to input their choice.
- End.
choice = 'restart';
while choice == 'restart':
choice = raw_input('What do you want? ')
print 'Break!'
Here, while True
results in misleading and overly complex code.
Breaking out of a while loop and switch in one go
Wrap the whole thing in a function, then you can simply return
to break out of both.
var input = prompt();
(function () {
while(true) {
switch(input) {
case 'hi':
break;
case 'bye':
return;
}
/*Other code*/
}
})();
Java How can I break a while loop under a switch statement?
You can label
your while loop, and break
the labeled loop
, which should be like this:
loop: while(sc.hasNextInt()){
typing = sc.nextInt();
switch(typing){
case 0:
break loop;
case 1:
System.out.println("You choosed 1");
break;
case 2:
System.out.println("You choosed 2");
break;
default:
System.out.println("No such choice");
}
}
And the label
can be any word you want, for example "loop1"
.
How do I break from a while loop with a switch?
You get an infinite loop because that's not how break
works. Once the first break
executes, you exit the switch
statement and the second break
never executes. You'll have to find another way to exit the outer control structure. For example, set a flag in the switch
statement, and then check that flag at the end, or in the loop condition.
while (std::cin >> n)
{
bool should_continue = true;
switch (n)
{
case 4:
should_continue = false;
break;
default:
std::cout << "Incorrect";
break;
}
if (!should_continue)
break;
}
Does break in a switch-statement terminates a for-loop?
You can break
a switch
. You can't break
an if
. break
is applied to the closest statement that could be break
ed, so
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
// using break statement inside the inner loop
break;
}
System.out.println(i + " " + j);
}
Here break
refers to the for
.
While here:
for (int i = 0; i < 3; i++) {
String line = null;
switch (a) {
case 0:
line = "Hello";
break;
It refers to the switch
.
Statements that can be break
ed are for
, while
, do...while
, switch
.
For further info, you can see the spec.
Breaking out of a 'for' loop from a ''case statement
Yes, break will break out of the closest loop or switch. The easiest way is to use a goto. (No, goto is not evil)
for {
switch(...) {
....
goto MyLabel;
}
}
MyLabel:
Related Topics
Checking File/Folder Access Permission
How to Pass Values Between Forms in C# Windows Application
C# Split String and Remove Empty String
Static Binding Doesn't Update When Resource Changes
Camera.Main Is Null When Performing Raycast
An Object Reference Is Required for the Non-Static Field, Method, or Property
Persist Data by Programming Against Interface
Replace Unicode Escape Sequences in a String
Image in Wpf Button Not Visible at Runtime
How to Read Single Excel Cell Value
How to Load Assemblies Located in a Folder in .Net Core Console App
How to Communicate with a Windows Service
Memory Efficiency and Performance of String.Replace .Net Framework