[c++] How do I "break" out of an if statement?

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;
...
}

This question is related to c++

The answer is


if (test)
{
    ...
    goto jmp;
    ...
}
jmp:

Oh why not :)


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.


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


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


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.


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


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

switch(colour)
{
  case red:
  {
    switch(car)
    { 
      case hyundai: 
      {
        break;
      }
      :
    }
    break;
  }
  :
}

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.


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: