如何从 if 语句中“断开”?

我有一个 if 语句,我想“突破”出来。我知道中断只是为了循环。有人能帮忙吗?

对于那些需要一个例子来说明我正在做什么的人:

if( color == red )
{
...
if( car == hyundai ) break;
...
}
366796 次浏览

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();
}

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

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.

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.

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

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.

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

Oh why not :)

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:

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

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