159

I'm writing some code that looks like this:

while(true) {
    switch(msg->state) {
    case MSGTYPE: // ... 
        break;
    // ... more stuff ...
    case DONE:
        break; // **HERE, I want to break out of the loop itself**
    }
}

Is there any direct way to do that?

I know I can use a flag, and break from the loop by putting a conditional break just after the switch. I just want to know if C++ has some construct for this already.

user229044
  • 232,980
  • 40
  • 330
  • 338
jrharshath
  • 25,975
  • 33
  • 97
  • 127
  • 23
    Why do you need a conditional break after the switch? Just change your while from while(true) to while(flag)... – Tal Pressman Sep 14 '09 at 07:02
  • 9
    @Dave_Jarvis I assume that this is a simplified version that he has put in here to illustrate what he was trying to do. – Alterlife Sep 14 '09 at 07:50
  • See: Code Complete (2nd Edn). See also 'Structured Programming with goto statements' by D E Knuth (http://pplab.snu.ac.kr/courses/adv_pl05/papers/p261-knuth.pdf). – Jonathan Leffler Sep 14 '09 at 07:52
  • 1
    @Tal Pressman et al: it looks like it could be a state table machine to me, with one case for each state - including a DONE state in which the code should exit. However, that could perhaps be handled by '`while (msg->state != DONE)`' for the loop control. – Jonathan Leffler Sep 14 '09 at 07:54
  • @Jonathan. Yes, exactly. I would go one further and separate the concerns of the loop's terminating condition from the loop itself (extract it to a method). – Dave Jarvis Sep 14 '09 at 08:31
  • 6
    If you are one of these programmers that produce functions which are several pages long, you'll find `goto` appealing and, sometimes, the only clean way out. If you tend to organize your code into small functions which are only a few lines long and do one single thing each, you will never run into this problem. (Incidentally your code will be easier to read, too.) – sbi Sep 14 '09 at 09:40
  • 17
    If feels like getting an advice to quit smoking when all you want to know is how to get to the nearest subway station. – Michael Krelin - hacker Sep 14 '09 at 09:54
  • 8
    @hacker: Well, if you can't see the subway station in front of you due to all the smoke, that advice might not be all that bad. `:)` – sbi Sep 15 '09 at 12:34
  • Sometimes it's convenient to call return from a case. Not pretty, but works. – Dmitry Vyal Aug 20 '13 at 14:48
  • You can always use if-else, unless you have too many cases..! – xcorat Jan 25 '17 at 15:41
  • @sbi If you are one of those programmers who only write functions which are only a few lines long, then by definition you are not using/writing (well formatted) switch-case statements ;) (depending on your definition of "few") But yes, you can usually break it up a bit (move the while loop into its own function, use return)... though it won't always make the code more readable. If I grouped every pair of statements into a function then I could write code that reads like a binary tree :) Just try writing readable chunks that belong together so looking up functions doesn't break flow of reading. – Steven Spark Nov 13 '19 at 01:59
  • @Steven Who said I group "every pair of statements into a function"? – sbi Jan 20 '20 at 18:54
  • @sbi I don't know? Who said it? I for sure didn't say that you did. I just tried to illustrate my point, that shorter doesn't always result more readable code. But it usually does, so it's a good practice to divide code to the shortest possible complete chunks, but not shorter IMO. [ I don't know how to move this conversation off of this comment thread, but I'm curious what you think about libtomcrypt's use of gotos. Do you have an elegant, more readable way of doing it? ] – Steven Spark Jun 15 '20 at 12:52

20 Answers20

221

You can use goto.

while ( ... ) {
   switch( ... ) {
     case ...:
         goto exit_loop;

   }
}
exit_loop: ;
Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
  • 16
    Just don't go wild with that keyword. – Fragsworth Sep 14 '09 at 06:56
  • 66
    It's funny I get downvoted because people don't like `goto`. The OP clearly mentioned *without using flags*. Can you suggest a better way, considering the OP's limitation? :) – Mehrdad Afshari Sep 14 '09 at 06:57
  • Pretty sure that is the only way to do it but unless you want spaghetti code, I would steer clear of goto. – dnatoli Sep 14 '09 at 06:57
  • +1: `goto` seems to be an ideal solution here. It would be improved if the `while` loop were also the sole constituent of a function or method. – quamrana Sep 14 '09 at 07:01
  • I don't say it's necessarily the ideal solution. Refactoring the code is probably a better idea. However, I believe it's a valid answer to this question. – Mehrdad Afshari Sep 14 '09 at 07:03
  • @Mehrdad, I suggested a way in my answer. But it is just for fun :) – Kirill V. Lyadvinsky Sep 14 '09 at 07:17
  • 24
    upvoted just t to compensate mindless goto haters. I guess Mehrdad knew he's going to lose a couple of points for suggesting sensible solution here. – Michael Krelin - hacker Sep 14 '09 at 07:17
  • 5
    +1. I understand this is more of a theoretical than a practical question; it clearly asks for a jump instruction. Given that break, continue and return are unsuitable, the only answer is the general jump: goto. This said, while (flag) would be a superior construct, but not what the OP asked for. – Gorpik Sep 14 '09 at 07:18
  • 2
    You know I was actually a bit surprised to see a `goto` answer. I'm glad you did, though, so I don't gotta. +1 – SingleNegationElimination Sep 14 '09 at 07:32
  • 5
    This is one of the very few areas I'd consider a goto. It's forward in direction and goes out of scopes rather than in. It implements a very easily understood concept. The problem with goto is that it's easy to use in an unstructured way (and that so few people use it that it's rather obscure). This is, in my opinion, an acceptable and appropriate use. – David Thornley Sep 14 '09 at 17:18
  • 7
    +1, there is no better way imho, even when considering the OPs limitations. Flags are ugly, break up logic across the whole loop and thus more difficult to grasp. – Johannes Schaub - litb Sep 14 '09 at 17:46
  • 18
    at the end of the day, without the goto construct, all languages fail. high level languages obfuscate it, but if you look hard enough under the hood, you will find every loop, or condition boils down to conditional and unconditional branches. we fool ourselves by using for,while,until, switch,if keywords, but eventually they all utilise GOTO (or JMP) in one way or the other. you can delude yourself, inventing all sorts of clever way to hide it, or you can just be pragmatically honest, and use goto, where appropriate, and sparingly. – unsynchronized Aug 31 '12 at 22:47
  • Personally, I have never, and will never, use a goto. Unless I'm writing assembly, where it's spelled JMP. – Dave Branton Mar 07 '17 at 23:44
  • Probably the person meant without flags, without goto. Morally, there should be a way to break from a loop and switch statement! Why did they use the same keyword???? –  May 30 '19 at 21:25
  • For all the goto haters: https://opensource.apple.com/source/xnu/xnu-792/libkern/stdio/scanf.c.auto.html , https://elixir.bootlin.com/linux/latest/source/drivers/usb/core/usb.c https://github.com/embeddedartists/labtool/blob/master/fw/Lib_USB/LPCUSBLib/Drivers/USB/Core/HostStandardReq.c http://www.verysource.com/code/30591516_1/usbcore.c.html :) Goto can be useful for freeing up resources after detecting error, zeroing out buffers after crypt (PolarSSL, libtomcrypt)... without expensive exceptions or even C++... – Steven Spark Nov 13 '19 at 02:19
80

An alternate solution is to use the keyword continue in combination with break, i.e.:

for (;;) {
    switch(msg->state) {
        case MSGTYPE:
            // code
            continue; // continue with loop
        case DONE:
            break;
    }
    break;
}

Use the continue statement to finish each case label where you want the loop to continue and use the break statement to finish case labels that should terminate the loop.

Of course this solution only works if there is no additional code to execute after the switch statement.

sakra
  • 62,199
  • 16
  • 168
  • 151
  • 18
    While this is indeed very elegant, it has the disadvantage that most developers first have to look at it for a minute in order to understand how/whether this works. `:(` – sbi Sep 15 '09 at 12:27
  • 10
    The last sentence is what makes this not so great `:(` Otherwise a very clean implementation. – nawfal Oct 15 '13 at 10:11
  • When you think about it, no computer code is good. We are only trained to understand it. For example xml looked like garbage until I learnt it. Now it is less garbage looking. for(int x=0; x<10; ++x, moveCursor(x,y)) actually caused a logic error in my program. I forgot that the update condition happened at the end. –  May 30 '19 at 21:35
  • Brilliant in its simplicity. Just what I needed. Thanks! – Jean-David Lanz Jan 19 '22 at 09:57
  • elegant but kind of counterintuitive, thanks for this solution – Kevin Chan Oct 26 '22 at 06:06
55

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.)

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:

  1. Isolates the knowledge of the loop's workload from the loop itself.
  2. Allows someone maintaining the code to easily extend the functionality.
  3. Allows multiple terminating conditions to be assigned in one place.
  4. Separates the terminating clause from the code to execute.
  5. 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:

  1. Loop forever.
  2. Ask the user to input their choice.
  3. If the user's input is 'restart', continue looping forever.
  4. Otherwise, stop looping forever.
  5. End.
Code
while True: 
    choice = raw_input('What do you want? ')

    if choice == 'restart':
        continue
    else:
        break

print 'Break!' 

Versus:

  1. Initialize the user's choice.
  2. Loop while the user's choice is the word 'restart'.
  3. Ask the user to input their choice.
  4. End.
Code
choice = 'restart';

while choice == 'restart': 
    choice = raw_input('What do you want? ')

print 'Break!'

Here, while True results in misleading and overly complex code.

Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
  • See: Code Complete (2nd Edn). See also 'Structured Programming with goto statements' by D E Knuth (http://pplab.snu.ac.kr/courses/adv_pl05/papers/p261-knuth.pdf). – Jonathan Leffler Sep 14 '09 at 07:46
  • 1
    Although the title of this answer may not be the best - I'd say the _content_ is very good and well explained. You'd never see while(true) in any of my code and this post explains all of the reasons why. Up vote from me. – Paulius Sep 14 '09 at 08:00
  • 61
    The idea that `while(true)` should be harmful seems bizarre to me. There's loops that check before they execute, there's those that check afterwards, and there's those that check in the middle. Since the latter don't have syntactic construct in C and C++, you'll have to use `while(true)` or `for(;;)`. If you consider this wrong, you haven't given enough thought to the different kind of loops yet. – sbi Sep 14 '09 at 09:37
  • 39
    Reasons why I disagree: while(true) and for(;;;) are not confusing (unlike do{}while(true)) because they state what they're doing right up front. It is actually easier to look for "break" statements than parse an arbitrary loop condition and look for where it's set, and no harder to prove correctness. The argument about where to put code is just as intractable in the presence of a continue statement, and not much better with if statements. The efficiency argument is positively silly. – David Thornley Sep 14 '09 at 17:15
  • 28
    Whenever you see "while(true)", you can think of a loop that has internal termination conditions, which are no harder than arbitrary end conditions. Simply, a "while(foo)" loop, where foo is a boolean variable set in an arbitrary way, is no better than "while(true)" with breaks. You have to look through the code in both cases. Putting forth a silly reason (and microefficiency is a silly argument) doesn't help your case, by the way. – David Thornley Sep 14 '09 at 17:49
  • 1
    @Dave Jarvis: We do seem to have some serious differences of opinion. Personally, I don't see that typing /break is any harder than looking for where a sentinel variable changes (and the original example would require a sentinel variable if there was any processing to be done if msg->state == DONE). I looked for efficiencies in the Knuth article, and found stuff that was basically irrelevant (12% improvement from adding a sentinel value) and stuff that was valid 35 years ago. I saw nothing applicable to while(true) at all. – David Thornley Sep 14 '09 at 20:08
  • 6
    @Dave: I gave a reason: It's the only way to get a loop that checks the condition in the middle. Classic example: `while(true) {string line; std::getline(is,line); if(!is) break; lines.push_back(line);}` Of course I could transform this to a preconditioned loop (using `std::getline` as the loop condition), but this has disadvantages on its own (`line` would have to be a variable outside the loop's scope). And if I did, I would have to ask: Why do we have three loops anyway? We could always transform everything into a preconditioned loop. Use what fits best. If `while(true)` fits, then use it. – sbi Sep 15 '09 at 09:07
  • 2
    @Dave Jarvis: the `continue` in your python code is totally unnecessary. Initializing `choice` with some dummy value is the error prone part. – Daniel Oct 04 '16 at 08:13
  • 1
    Single process, single thread bare metal embedded code is always inside while (1). – Vagish Dec 03 '18 at 16:56
  • 3
    As a courtesy to people reading this answer, I would avoid commenting on the quality of the good that produced the question and stick to answering the question itself. The question is a variation on the following, which I believe is a feature of many languages: you have a loop nested inside of another loop. You want to break out of the outer loop from the inner loop. How is this done? – Alex Leibowitz Jun 30 '19 at 23:50
  • 2
    This answer completely ignores the very valid case of a loop with termination condition somewhere in the middle (if that wasn't an appropriate use case we wouldn't even have a break keyword after all) for the sake of demonizing goto. Transforming a `while(true)` loop with a break in the middle into a `while(cond)` or `do{}while(cond)` form would require either an artificial flag or code duplication, both of which are harder to read and argue about. Finally, if you are worried about performance implications of `while(true)` you can always change it to `for(;;)` – Askaga Aug 15 '19 at 06:29
27

A neatish way to do this would be to put this into a function:

int yourfunc() {

    while(true) {

        switch(msg->state) {
        case MSGTYPE: // ... 
            break;
        // ... more stuff ...
        case DONE:
            return; 
        }

    }
}

Optionally (but 'bad practices'): as already suggested you could use a goto, or throw an exception inside the switch.

Alterlife
  • 6,557
  • 7
  • 36
  • 49
  • 4
    Exception should be used to, well, throw an exception, not a well know behavior of a function. – Clement Herreman Sep 14 '09 at 07:04
  • I agree with Afterlife: Put it in a function. – dalle Sep 14 '09 at 07:06
  • 19
    Throwing an exception is really evil in this case. It means "I want to use a goto, but I read somewhere that I should not use them, so I'll go with a subterfuge and pretend to look smart". – Gorpik Sep 14 '09 at 07:07
  • I agree that throwing an exception or using a goto is a terrible idea, but they are working options and have been listed as such in my answer. – Alterlife Sep 14 '09 at 07:53
  • 2
    Throwing an exception is substituting a COMEFROM for a GOTO. Don't do it. The goto works much better. – David Thornley Sep 14 '09 at 17:19
16

AFAIK there is no "double break" or similar construct in C++. The closest would be a goto - which, while it has a bad connotation to its name, exists in the language for a reason - as long as it's used carefully and sparingly, it's a viable option.

Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
Amber
  • 507,862
  • 82
  • 626
  • 550
10

You could put your switch into a separate function like this:

bool myswitchfunction()
{
    switch(msg->state) {
    case MSGTYPE: // ... 
        break;
    // ... more stuff ...
    case DONE:
        return false; // **HERE, I want to break out of the loop itself**
    }
    return true;
}

while(myswitchfunction())
    ;
Adam Pierce
  • 33,531
  • 22
  • 69
  • 89
8

Even if you don't like goto, do not use an exception to exit a loop. The following sample shows how ugly it could be:

try {
  while ( ... ) {
    switch( ... ) {
      case ...:
        throw 777; // I'm afraid of goto
     }
  }
}
catch ( int )
{
}

I would use goto as in this answer. In this case goto will make code more clear then any other option. I hope that this question will be helpful.

But I think that using goto is the only option here because of the string while(true). You should consider refactoring of your loop. I'd suppose the following solution:

bool end_loop = false;
while ( !end_loop ) {
    switch( msg->state ) {
    case MSGTYPE: // ... 
        break;
    // ... more stuff ...
    case DONE:
        end_loop = true; break;
    }
}

Or even the following:

while ( msg->state != DONE ) {
    switch( msg->state ) {
    case MSGTYPE: // ... 
        break;
    // ... more stuff ...
}
Community
  • 1
  • 1
Kirill V. Lyadvinsky
  • 97,037
  • 24
  • 136
  • 212
  • 1
    Yeah, but **I** like exceptions even less ;-) – quamrana Sep 14 '09 at 07:20
  • 4
    Using an exception to emulate a goto is of course worse than actually using a goto! It will probably also be significantly slower. – John Carter Sep 14 '09 at 07:22
  • 2
    @Downvoter: It is because I state, that you shouldn't use exception, or because I suggest refactoring? – Kirill V. Lyadvinsky Sep 14 '09 at 07:29
  • 1
    Not the down-voter - but... Your answer isn't clear whether you are proposing or condemning the idea of using an exception to exit the loop. Maybe the first sentence should be: "Even if you don't like `goto`, do **not** use an exception to exit a loop:"? – Jonathan Leffler Sep 14 '09 at 07:50
  • 1
    @Jonathan Leffler, Thanks, you showed the sample of valuable comment. updated the answer keeping in mind your comments. – Kirill V. Lyadvinsky Sep 14 '09 at 08:42
5

There's no C++ construct for breaking out of the loop in this case.

Either use a flag to interrupt the loop or (if appropriate) extract your code into a function and use return.

sharptooth
  • 167,383
  • 100
  • 513
  • 979
5

No, C++ does not have a construct for this, given that the keyword "break" is already reserved for exiting the switch block. Alternatively a do..while() with an exit flag could suffice.

do { 
    switch(option){
        case 1: ..; break;
        ...
        case n: .. ;break;
        default: flag = false; break;
    }
} while(flag);
2

You could potentially use goto, but I would prefer to set a flag that stops the loop. Then break out of the switch.

Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
Martin York
  • 257,169
  • 86
  • 333
  • 562
2

Why not just fix the condition in your while loop, causing the problem to disappear?

while(msg->state != DONE)
{
    switch(msg->state) {
    case MSGTYPE: // ... 
        break;
    // ... more stuff ...
    case DONE:
        // We can't get here, but for completeness we list it.
        break; // **HERE, I want to break out of the loop itself**
    }
}
Mark B
  • 95,107
  • 10
  • 109
  • 188
1

I think;

while(msg->state != mExit) 
{
    switch(msg->state) 
    {
      case MSGTYPE: // ...
         break;
      case DONE:
      //  .. 
      //  ..
      msg->state =mExit;
      break;
    }
}
if (msg->state ==mExit)
     msg->state =DONE;
ercan
  • 11
  • 1
1

I got same problem and solved using a flag.

bool flag = false;
while(true) {
    switch(msg->state) {
    case MSGTYPE: // ... 
        break;
    // ... more stuff ...
    case DONE:
        flag = true; // **HERE, I want to break out of the loop itself**
    }
    if(flag) break;
}
Ram Suthar
  • 356
  • 2
  • 9
1

It amazes me how simple this is considering the depth of explanations... Here's all you need...

bool imLoopin = true;

while(imLoopin) {

    switch(msg->state) {

        case MSGTYPE: // ... 
            break;

        // ... more stuff ...

        case DONE:
            imLoopin = false;
            break;

    }

}

LOL!! Really! That's all you need! One extra variable!

Mark A. Donohoe
  • 28,442
  • 25
  • 137
  • 286
  • for this specific example, sure. but the depth of explanations are warranted to answer the general question "How to break out of a loop from inside the switch" – Michael Sep 01 '23 at 11:12
  • 1
    Lol... well I was a different person twelve years ago my friend. – Mark A. Donohoe Sep 02 '23 at 04:11
1

Because the switch uses the break to break out from the switch (not from the while(1)), it needs the goto-statement:

while(1) {
    switch (*p) {
      case ' ':
        p++;
        break;
      case '\n':
        p++; *s=p; return(i);
      case '\0':
        *s=p; return(i);
      default:
        token[i]=p;
        i++;
        p++;
        goto ex1;
    };
  };
  ex1:

I can't add multiple case to same line like:

case ' ','\t':

it would be

case ' ': case '\t':

That's why maybe the break used here...

It looks the most frequent cases should be placed at the top of the list to make the program run faster. It may not have parallel execution for searching the different cases.

It is possible that the standard c then has missing some methods about this switching: https://blog.hackajob.co/better-c-switch-statements-for-a-range-of-values/ => allows you to use the <, >, <=, and >= operators in a switch expression

I was thinking that it should be (if c-language syntax changed) like:

switch (c) {
  case >= 5:
     ... op1
  endcase;
  case == 1:
  case == 3:
     ... op2
  endcase;
  default:
    ...
};

where op2 is executed when c is equal to 1 or 3 and when c is larger than or equal to 5 op1 is executed. Because comparison for equal or larger/smaller than would occur easily in similar manner.

  while(1) {
    switch (c) {
      case >= 2:
         ... op1
      case <= 5:
         ... op2
      break;
      default:
        ...
    };
  };

this case op1 is executed for c larger than 2 and op2 executed for 2<=c<=5 and break exits it from while-loop.

user1070696
  • 301
  • 2
  • 4
0

The simplest way to do it is to put a simple IF before you do the SWITCH , and that IF test your condition for exiting the loop .......... as simple as it can be

0

The break keyword in C++ only terminates the most-nested enclosing iteration or switch statement. Thus, you couldn't break out of the while (true) loop directly within the switch statement; however you could use the following code, which I think is an excellent pattern for this type of problem:

for (; msg->state != DONE; msg = next_message()) {
    switch (msg->state) {
    case MSGTYPE:
        //...
        break;

    //...
    }
}

If you needed to do something when msg->state equals DONE (such as run a cleanup routine), then place that code immediately after the for loop; i.e. if you currently have:

while (true) {
    switch (msg->state) {
    case MSGTYPE:
        //... 
        break;

    //...

    case DONE:
        do_cleanup();
        break;
    }

    if (msg->state == DONE)
        break;

    msg = next_message();
}

Then use instead:

for (; msg->state != DONE; msg = next_message()) {
    switch (msg->state) {
    case MSGTYPE:
        //...
        break;

    //...
    }
}

assert(msg->state == DONE);
do_cleanup();
Daniel Trebbien
  • 38,421
  • 18
  • 121
  • 193
0
while(MyCondition) {
switch(msg->state) {
case MSGTYPE: // ... 
    break;
// ... more stuff ...
case DONE:
   MyCondition=false; // just add this code and you will be out of loop.
    break; // **HERE, you want to break out of the loop itself**
}
}
Wajeed Shaikh
  • 3,078
  • 1
  • 23
  • 30
-2

If I remember C++ syntax well, you can add a label to break statements, just like for goto. So what you want would be easily written:

while(true) {
    switch(msg->state) {
    case MSGTYPE: // ...
        break;
    // ... more stuff ...
    case DONE:
        break outofloop; // **HERE, I want to break out of the loop itself**
    }
}

outofloop:
// rest of your code here
Andrei Vajna II
  • 4,642
  • 5
  • 35
  • 38
  • 1
    Unfortunately, your memory is faulty. It would be a nice feature, on those rare occasions where it would be useful. (I've seen proposals for number of levels to break from, but those look to me like bugs waiting to happen.) – David Thornley Sep 14 '09 at 20:10
  • That must have been Java, then. Thanks for answering. And, of course, you're right with the rest, too. – Andrei Vajna II Sep 14 '09 at 20:31
-3
  while(true)
  {
    switch(x)
    {
     case 1:
     {
      break;
     }
    break;
   case 2:
    //some code here
   break;
  default:
  //some code here
  }
}
Flexo
  • 87,323
  • 22
  • 191
  • 272