Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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; ... } 
like image 521
Wes Avatar asked Dec 15 '11 16:12

Wes


People also ask

Can you break out of an if statement?

You can't break out of if statement until the if is inside a loop. The behaviour of the break statement is well specified and, generally, well understood. An inexperienced coder may cause crashes though a lack of understanding in many ways. Misuse of the break statement isn't special.

How do you break out of if statements but not for loops?

if statements are not loops; you don't 'break out' of them. When you use break inside an if statement, it will break out of the loop that directly encloses it (in this case, the for loop). break is not treated any differently inside an if block.

How do you break out of an IF statement in Python?

In Python, the break statement provides you with the opportunity to exit out of a loop when an external condition is triggered. You'll put the break statement within the block of code under your loop statement, usually after a conditional if statement.


2 Answers

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(); } 
like image 199
phoog Avatar answered Sep 25 '22 09:09

phoog


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

Oh why not :)

like image 36
Matt Phillips Avatar answered Sep 22 '22 09:09

Matt Phillips