How can I escape from an if statement?

I have an if statement that I want to break. I understand that a break is really only a loop. Can anyone help?

For those who need an example of what I'm trying to do:

if( color == red ) { ... if( car == hyundai ) break; ... } 
+50
c ++
Dec 15 '11 at 16:41
source share
10 answers

Nested ifs:

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

At the risk of being slowed down - it happened to me in the past - I mentioned that the other (unpopular) option, of course, would be the scary goto ; the expression about the break is simply disguised.

And finally, I will repeat the general opinion that your design can probably be improved so that the mass if statement is not necessary, not to mention its exit from it. At the very least, you should be able to extract several methods and use return:

 if (condition) { ExtractedMethod1(); if (breakOutCondition) return; ExtractedMethod2(); } 
+54
Dec 15 '11 at 16:44
source share
 if (test) { ... goto jmp; ... } jmp: 

Oh why not :)

+32
Dec 15 '11 at 16:47
source share

You probably need to break the if statement into smaller parts. In doing so, you can do two things:

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

  • put the instruction in your own routine and use return This may be the first step to improving your code.

+16
Dec 15 '11 at 16:46
source share

You cannot break break from 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 will give "var = 1" as output

+3
Dec 15 '11 at 16:46
source share

There is always a goto statement , but I would recommend inserting an if with the opposite condition of violation.

+2
Dec 15 '11 at 16:44
source share

You can use the shortcut and goto , but this is a bad hack. You should consider moving some elements in your if statement to separate methods.

+2
Dec 15 '11 at 16:44
source share

Operators || and && are short circuits, therefore, if the left side is || evaluates to true or the left side && is false, the right side will not be evaluated. This is equivalent to a break.

+2
Dec 15 '11 at 16:45
source share

You have a shortcut at the point you want to go to and aside if you use go

 if(condition){ if(jumpCondition) goto label } label: 
+2
Dec 15 '11 at 16:50
source share

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

+1
Dec 15 '11 at 16:45
source share

I do not know your test conditions, but a good old switch could work

 switch(colour) { case red: { switch(car) { case hyundai: { break; } : } break; } : } 
+1
Dec 15 '11 at 16:52
source share



All Articles