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;
...
}
12
  • 3
    Sorry nobody can help. Voted for close. Nobody can help if you don't give us some detail with some code snippet Dec 15, 2011 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, 2011 at 16:43
  • 4
    If it's within a function, you could use "return".
    – poitroae
    Dec 15, 2011 at 16:44
  • 4
    have you tried goto although it is not recommended
    – Emmanuel N
    Dec 15, 2011 at 16:44
  • 3
    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. Mar 22, 2018 at 7:03

10 Answers 10

88

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();
}
6
  • 8
    Refactoring chunks into functions will not only help readability but possibly solve the original problem too.
    – Mark B
    Dec 15, 2011 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. Dec 15, 2011 at 17:49
  • 9
    goto is a fine solution if for variable scope reasons you cannot call another function. Dec 15, 2011 at 17:54
  • 18
    goto looks a heck of a lot cleaner that nested-if after nested-if.
    – Adam S
    Jul 15, 2014 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, 2014 at 17:10
57
if (test)
{
    ...
    goto jmp;
    ...
}
jmp:

Oh why not :)

8
  • 1
    Eww... I smell some facetiousness in this answer. Not that it's technically incorrect, of course.
    – Yuck
    Dec 15, 2011 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. Dec 15, 2011 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. May 4, 2016 at 5:45
  • 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. Aug 20, 2019 at 8: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. Nov 13, 2019 at 7:28
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
  • 7
    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, 2011 at 16:51
  • I'd agree it's a better solution than goto.
    – user3458
    Dec 15, 2011 at 16:54
  • @phoog, probably, but I wouldn't know, the question is tagged C++, where it doesn't...
    – Nim
    Dec 15, 2011 at 16:55
  • @Nim ack, how did I miss that?
    – phoog
    Dec 15, 2011 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, 2011 at 19:02
3

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.

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;
  }
  :
}
2

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

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.

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

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:
1

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.