91

I have a if statement that I want to "break" out of. I understand that break is only really for loops. Can anyone help?

For those that require an example of what I'm trying to do:

if( color == red )
{
...
if( car == hyundai ) break;
...
}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Wes
  • 4,781
  • 7
  • 44
  • 53
  • 3
    Sorry nobody can help. Voted for close. Nobody can help if you don't give us some detail with some code snippet – Nawaz Dec 15 '11 at 16:43
  • Show the code that represents what you're trying to do. – Matt Ball Dec 15 '11 at 16:43
  • 2
    Can you give a little bit of sample code? And depending on the situation, you could try a `switch` block instead; they do support breaking. – piebie Dec 15 '11 at 16:43
  • 4
    If it's within a function, you could use "return". – poitroae Dec 15 '11 at 16:44
  • 3
    have you tried `goto` although it is not recommended – Emmanuel N Dec 15 '11 at 16:44
  • Don't do it. Doing it is similar to using a "goto" command and should be avoided in most (if not all) cases. Make sure you structure your logic flow better to avoid having to use it. – Mihalis Bagos Dec 15 '11 at 16:47
  • Your initial description was confusing. You don't have a massive `if` statement, you have a massive series of `if` statements. Totally different thing. – Mark Ransom Dec 15 '11 at 17:00
  • It's amazing how many answers offer `goto` as the only option (5 at the time of writing this comment) – Walter Dec 15 '11 at 17:31
  • for(;color == red;){ ... if( car == hyundai ) break; ... } – DarkZeros Aug 02 '13 at 13:02
  • 2
    I have an easy fix for this. Use a do{}whie(false); outside the if statement. Doing so there are no code modifications required and the user can always use break statement whenever he wants. I wanted to post this as an answer, but this question is marked as closed. – IAmSurajBobade Mar 22 '18 at 07:03
  • 1
    while(color==red) { ... if (car==hyunai) {break;} ... break;} Can replace all if statements with while statements that have break at the end. – user3015682 Apr 16 '20 at 16:32
  • the question is decently written. It's NOT difficult to tell what is being asked here. This question is NOT ambiguous, vague, incomplete, overly broad, or rhetorical and CAN be reasonably answered. Similar question have an answer https://stackoverflow.com/questions/6302227/how-to-break-out-of-a-function – Bogdan Jan 08 '21 at 04:31

10 Answers10

86

Nested ifs:

if (condition)
{
    // half-massive amount of code here

    if (!breakOutCondition)
    {
        //half-massive amount of code here
    }
}

At the risk of being downvoted -- it's happened to me in the past -- I'll mention that another (unpopular) option would of course be the dreaded goto; a break statement is just a goto in disguise.

And finally, I'll echo the common sentiment that your design could probably be improved so that the massive if statement is not necessary, let alone breaking out of it. At least you should be able to extract a couple of methods, and use a return:

if (condition)
{
    ExtractedMethod1();

    if (breakOutCondition)
        return;

    ExtractedMethod2();
}
phoog
  • 42,068
  • 6
  • 79
  • 117
  • 8
    Refactoring chunks into functions will not only help readability but possibly solve the original problem too. – Mark B Dec 15 '11 at 17:10
  • Definitely in agreement with your second observation. However I would say the better path would be to refine the original `condition`, and add new ones as necessary, so that the block of code that is entered when it is satisfied corresponds to what should be executed *before* the break in OP's original idea. This would as in your example simply invoke a method, which could then be called in `condition2`, `condition3` etc. blocks as needed. – Matt Phillips Dec 15 '11 at 17:49
  • 9
    `goto` is a fine solution if for variable scope reasons you cannot call another function. – edA-qa mort-ora-y Dec 15 '11 at 17:54
  • 18
    `goto` looks a heck of a lot cleaner that nested-if after nested-if. – Adam S Jul 15 '14 at 23:35
  • 2
    @AdamS That's largely true -- especially if your font size is large or your code editor window narrow. However, adding `goto` tends to cause a more rapid increase in the difficulty of reasoning about a routine than adding nested `if` statements. So in a complicated method, I would probably favor ease of understanding control flow over cleanliness. – phoog Jul 30 '14 at 17:10
  • To play devil's advocate, often `void newFunc { if (whatever) return; doMoreStuff(); }` is not actually any better than `if (whatever) goto labelAfterIf; doMoreStuff(); labelAfterIf:`. In such cases, splitting things into separate methods just to avoid `goto`, out of the misguided sense of purity usually associated with said keyword, seems like a waste of time. Of course, in other cases it might create new benefits of its own, but I don't think it would be my default solution personally. Having said that, I've never needed to use either option, so I must be doing something right? :D – underscore_d Apr 06 '16 at 10:11
55
if (test)
{
    ...
    goto jmp;
    ...
}
jmp:

Oh why not :)

Matt Phillips
  • 9,465
  • 8
  • 44
  • 75
  • 1
    Eww... I smell some facetiousness in this answer. Not that it's technically incorrect, of course. – Yuck Dec 15 '11 at 17:29
  • 26
    @Yuck Nice relevant username. As for facetiousness, well a little but I would say that if your design forces you into OPs situation to begin with, then using a goto won't make it worse. Also phoog notes in his winning answer that nested conditionals are really only superficially different. – Matt Phillips Dec 15 '11 at 17:45
  • Sometimes you're dealing with someone else's smelly code, and you don't have a few hours/days to refactor it into something sane...r. – kayleeFrye_onDeck May 04 '16 at 05:45
  • Goog, clean, nice solution in old-fashion manner –  Jul 27 '16 at 13:10
  • goto is always frowned on by academics for some reason. But in the real world, there are valid use cases where it actually a much simpler. solution to implement than a bunch of complicated IF conditions. It can make the code easier to read and understand. Having said that, those situations are extremely rare. – hookenz Jun 18 '19 at 04:20
  • 2
    Problem with goto is not with the initial implementation. It's during enhancement when another developer adds a few statements between the end of if braces and jmp: statement unknowingly. – Mandeep Singh Aug 20 '19 at 08:23
  • 2
    @MandeepSingh Is it even possible to write code that guards against developers from doing unholy things with it? Even if they do stupid things with it, chances are that they frequently do stupider things in other parts of the code anyways. – Mateen Ulhaq Nov 13 '19 at 07:28
  • I think goto in this case make the code much clearer and easier to manage than nested-if etc – kstn Aug 15 '21 at 14:01
24

You probably need to break up your if statement into smaller pieces. That being said, you can do two things:

  • wrap the statement into do {} while (false) and use real break (not recommended!!! huge kludge!!!)

  • put the statement into its own subroutine and use return This may be the first step to improving your code.

  • 6
    I've seen the `do/while` technique used and I wouldn't necessarily consider it a kludge it works nicely and avoids problems `goto` may introduce (for example attempting to jump across variable initialization) – Nim Dec 15 '11 at 16:51
  • I'd agree it's a better solution than goto. –  Dec 15 '11 at 16:54
  • @phoog, probably, but I wouldn't know, the question is tagged C++, where it doesn't... – Nim Dec 15 '11 at 16:55
  • @Nim ack, how did I miss that? – phoog Dec 15 '11 at 16:57
  • +1, other than the extra level of indenting (which you'd have for half the code anyway with the accepted answer), this is probably ideal - it's like a controlled `goto`, and very close to "do what I mean" without a lot of cruft. – Izkata Dec 15 '11 at 19:02
  • +1 for the subroutine: it makes the code more clear and provides a place where to handle errors are perform any necessary cleanup – Julien-L Dec 18 '15 at 20:34
3

I don't know your test conditions, but a good old switch could work

switch(colour)
{
  case red:
  {
    switch(car)
    { 
      case hyundai: 
      {
        break;
      }
      :
    }
    break;
  }
  :
}
Nim
  • 33,299
  • 2
  • 62
  • 101
2

There's always a goto statement, but I would recommend nesting an if with an inverse of the breaking condition.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

You could use a label and a goto, but this is a bad hack. You should consider moving some of the stuff in your if statement to separate methods.

Daniel Gabriel
  • 3,939
  • 2
  • 26
  • 37
2

The || and && operators are short circuit, so if the left side of || evaluates to true or the left side of && evaluates to false, the right side will not be evaluated. That's equivalent to a break.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
2

You can't break break out of an if statement, unless you use goto.

if (true)
{
      int var = 0;
      var++;
      if (var == 1)
          goto finished;
      var++;
}

finished:
printf("var = %d\n", var);

This would give "var = 1" as output

DipSwitch
  • 5,470
  • 2
  • 20
  • 24
2

Have a label at a point you want to jump to and in side your if use goto

if(condition){
     if(jumpCondition) goto label
}
label:
Emmanuel N
  • 7,350
  • 2
  • 26
  • 36
1

You can use goto, return, or perhaps call abort (), exit () etc.