Half a croissant, on a plate, with a sign in front of it saying '50c'
h a l f b a k e r y
Oh yeah? Well, eureka too.

idea: add, search, annotate, link, view, overview, recent, by name, random

meta: news, help, about, links, report a problem

account: browse anonymously, or get an account and write.

user:
pass:
register,


                                                           

"break if" and "if break" statements in programming

 
(+2, -2)
  [vote for,
against]

in loops, these alias may be useful, by cutting down in code clutter. It also has the advantage of still being instantly identifiable in its purpose.

=========================

break if(statement); ---- breaks current loop if statement is true

} if break { ---- performs statement if the loop didn't end organically

========================

Example usage of above alias to break infinite loop:

------------------------------

int ever = TRUE;

for ( ever ){

__break if ( ever );

__alert( 'forever more!');

} if break {

__alert( 'loop ended prematurely' );

}

=======

Best usage for "break if", is possibly during recursive loops

======

edit: Perhaps we could also have "if break(flag)" or "if break[flag]", and "break(flag) if", if we have different breaking states.

e.g.

int number = 3;

for ( TRUE){

__break(1) if ( number == 1);

__break(2) if ( number == 2);

__break(3) if ( number == 3);

} if break(1) {

} if break(2) {

} if break(3) {

__alert("This alert has activated!");

}

--- EQUIV TO ---

int number = 3; int flag = null;

for ( TRUE){

if ( number == 1){flag=1;break;}

if ( number == 2){flag=2;break;}

if ( number == 3){flag=3;break;}

}

if ( flag == 1 ) {}

if ( flag == 2 ) {}

if ( flag == 3 ){alert("This alert has activated!");}

mofosyne, Feb 15 2012

COMEFROM Statement http://www.fortran.com/come_from.html
An alternative program-flow statement for your consideration. [zen_tom, Feb 20 2012]

[link]






       I've only programmed in a few languages, but I think things like this already exist, no?
MaxwellBuchanan, Feb 15 2012
  

       not that I seen   

       especially the "if break" statement, which would be a specialized alternative to "else if" statement   

       am hoping to see it used in python, as I can imagine this would be great use to keep code easy for newcomers to understand.
mofosyne, Feb 15 2012
  

       have you considered the "google" statement ?   

       I fail to understand.
FlyingToaster, Feb 15 2012
  

       Logically this is very similar to while() or repeat... until() statements. The idea of multiple breaks is dealt with by having ORs in the while() or until() condition.
hippo, Feb 15 2012
  

       yes but python *has* a 'break' keyword... coincidentally, at first glance anyways, it looks like it does exactly what [am] wants.
FlyingToaster, Feb 15 2012
  

       ---FlyingToaster, Feb 15 2012   

       I have googled it, and yes I know that generally the syntax tends to go like this   

       if (something) {break;}   

       All I'm asking is to also have   

       break if(something);   

       instead, as it is more intuitive. I don't think any programming language does that. Well not that I found in google at least.   

       Also for "} break if {" , it saves you from having to use 'flags' to identify if it fully looped or not.   

       ---hippo, Feb 15 2012   

       Yes it does seem not needed. I shall remove that usage example.
mofosyne, Feb 15 2012
  

       if(condition) break;   

       seems pretty reasonable to me. The break cases don't exist but could be implemented by wrapping the call into a seperate function:   

       int do_it() {   

       while(true) {   

       if(condition1) return 1;   

       if(condition2) return 2;   

       do_something_else();   

       }   

       }   

       OTOH: isn't that exactly what exceptions do?   

       try {   

       while(true) {   

       if(condition1) throw Exception1;   

       if(condition2) throw Exception2;   

       }   

       } catch (Exception1) {   

       do_stuff_1();   

       } catch (Exception2) {   

       do_stuff_2();   

       } finally {   

       do_stuff_finally();   

       }
fho, Feb 15 2012
  

       In C you can make a macro for "break if":   

       #define break_if (blah) if(blah){break;}
AntiQuark, Feb 15 2012
  

       You've given two examples:   

       the second, with the exception of the redundant logic, is easily handled by a "goto depending on", "alter"<insert big newbie warning here>, or a "case" type statement.   

       For the first, I can sortof see it if you're defining a very unusual exception condition. The machine doesn't care but using bass-ackwards syntax might make it easier for a programmer to parse a program-dependent logical exception.   

       But that's what comments are for.
FlyingToaster, Feb 15 2012
  

       "break if..." already exists in Ruby. It's just a case of the generalized form "<statement> if..." For example:

10.times do |x|
print x if x % 2 == 0
break if x == 5
end

Output: 024

The "if break" functionality doesn't exist per se, but since you can have a block return a specified value with the break statement, you can effectively emulate it (with more functionality) as follows:

case 10.times do |x|
print x if x % 2 == 0
break :error if x == 5
end
when :error
puts "ERROR"
end

Output: 024ERROR

So, in conclusion, you should just use Ruby, because everyone should use Ruby.
ytk, Feb 15 2012
  

       -ytk, Feb 15 2012   

       Can't argue against that logic. Wonder why the slower uptake of ruby compared to python. The ruby code does look a touch more cryptic than python.   

       As for "<statement> if...", this looks like something python should do.
mofosyne, Feb 16 2012
  

       I think the slower uptake is due to several factors, not the least of which is considerable head- start Python had over Ruby. Python was originally released four years prior to Ruby, and Ruby wasn't very well known outside of Japan for several years after its initial release. And since a significant part of both the Python and Ruby user base consists of Perl refugees, a lot of those people just ended up going to Python and staying there once they got sick of dealing with Perl, because it was essentially the only other game in town at the time. So only the ones (such as myself) who never really got along with Python ended up gravitating to Ruby once it became a viable option.   

       There also don't seem to be too many Python to Ruby converts. Ruby is an unbelievably flexible language, and I think that flexibility tends to put Python users off. Since everything in Ruby is an object, and every object can be modified more or less without restrictions, you can change or extend the entire language in pretty much any conceivable way. I guess you either appreciate and embrace that flexibility, or you fear it; in my experience, Python users tend to fear it. I'm not sure why, because while it might seem to make Ruby code a nightmare to follow and maintain, in actual practice Ruby tends to produce some of the most easily readable and maintainable code I've ever seen. I don't even bother commenting my code most of the time, because I rarely have trouble understanding programs I've written months or years ago. This stands in stark contrast to Perl, where even provided liberal comments throughout, my eyes would immediately glaze over upon reading the source to a program I'd written two weeks earlier.   

       In the end, I think it comes down largely to inertia. Admittedly, I have only limited experience with Python (although I've had to use it on occasion as it's the embedded scripting language in a few applications I use), but I really don't see why anyone who really puts in the effort to give Ruby an honest try would want to go back to Python. But since Python is a perfectly serviceable language (especially compared to Perl), I imagine most Python users don't feel much of a need to look into anything else. It's too bad, because they have no idea what they're missing (come to think of it, I feel the same way about Windows users too!)
ytk, Feb 16 2012
  

       I'm no expert and i only know prehistoric programming languages, but don't things like TIMEOUT, EXIT and LEAVE do this sort of thing?
nineteenthly, Feb 16 2012
  

       If you're trying to make your program clearer, then "if break" should definitely be "if broken"
mitxela, Feb 16 2012
  

       Ah, apologies for skipping past it.
mitxela, Feb 16 2012
  

       {if} break {if} considered harmful
Dub, Feb 17 2012
  

       I can't think of a situation where a variable would change mid-loop without an event, and for that you have event handlers which constantly monitor the state of that event.
marklar, Feb 20 2012
  

       What [Dub] said - you're basically talking "goto" here, which is kind of frowned upon by many, and is certainly controversial. Maybe it's more convenient in the short-term, but sticking to the loop/while convention isn't all that bad really.   

       You've also got the issue of making sure you know from which loop the break has exited from, if you're scanning through nested x and y indexes in a table structure and want to break out when you've found a search value, how do you know whether you've broken out of your x, or y loop?   

       Personally, I use a boolean value that I set to false prior to the the beginning of my loop, and on a breakable condition, I set it to true.   

       At the end of the loop structure, I test the boolean value and can determine whether I broke out of the loop (and if necessary, which one was broken out of) or if the loop continued to completion. It's not hard. (In fact, this seems to be pretty much what [bigsleep] is talking about a few annos up)   

       On the "goto considered harmful" thing - how about adopting the "comefrom" standard?
zen_tom, Feb 20 2012
  

       5760 REM DO NOT DELETE THIS LINE IT IS A TARGET FOR GOTOS   

       Ah, the "Good Old Days"…
8th of 7, Feb 20 2012
  

       //you're basically talking "goto" here//   

       Huh? This is nothing like goto. Transferring control to an arbitrary point in the program is completely different from transferring control to the point immediately following the current loop.   

       Besides, the idea is nothing more than syntactic sugar— simply an abbreviated form of "if( x ) { break; }". As I mentioned above, Ruby already has this. I use similar constructions all the time, and they're tremendously useful. For example:

# Find every .txt file in path

Find.find( path ) do |file|
next unless File.extname(file) == ".txt"
# Do something with the file here
end

# Find "foo.txt" if it exists in the given path

foo_location = Find.find( path ) { |file| break( file ) if File.basename( file ) == "foo.txt" }

Which part even remotely resembles a goto statement?
ytk, Feb 20 2012
  

       I don't know, it all depends on how far you go in before saying something is similar to something else. In terms of a transfer of program flow, then obviously, goto does that, as does break, as do a bunch of other things. Breakif in this context is at least anchored to the end of a loop, so in that respect it's better behaved than a goto might be. I accept that, fair enough. Back in the day, before even break existed, one of the only ways to break out of a loop early was by use of a goto.   

       Similarly in Assembly, going back to the early 80's, there's a bunch of "BRANCH ON" opcodes which are (kind of) equivalent to GOTO IF statements when used within a loop - it would of course be up to the coder to decide how to structure their code, and how far forward past such a loop structure someone might want to branch to, without being handheld by the system by syntactic conventions. And so in that respect, I see that there is a difference between having an additional loop clause that presupposes you will be branching out of it at some stage, and the more "wild-west" approach of allowing goto's all over the place. One's preference will always depend on whether one self-identifies as a cowboy or a sherriff - many people will have been both in their time, hence the cognitive dissonance.
zen_tom, Feb 20 2012
  

       // whether one self-identifies as a cowboy or a sherriff //   

       What if one self-identifies as a Mexican bandit ?   

       "Hgotos ... Hwee doan' need no steekning hgotos !"   

       There's a world of difference between a BRANCH embedded in pure Assembler, and the "break;" command - in Assembler, it's up to the programmer to make sure they unwind the stack correctly.
8th of 7, Feb 20 2012
  

       If I've understood [akimbomidget] correctly, he is suggesting that you can use 1 breakif statement at the beginning of the loop and it will exit the loop at any point. What everyone else seems to be suggesting is that you can write an if statement to exit at a specific point.   

       [zen_tom] your example is exiting a loop when it has served its purpose eg, do while(searchvalue != currentfield). Also, how do you set your boolean to true? from inside the loop or running parallel threads? Because the former is just an if statement and the latter is slightly above the level of my (and I suspect most others) programming knowledge.   

       [ytk] yours is also just a 'do while' with different syntax
marklar, Feb 21 2012
  

       Man, I think in autolisp this is the only option you actually have to simulate an if-then statement. Not an actual command as far as I know, but that's the logic of it all.   

       Do this until something is greater than that. If something is greater than that turn the lights off.   

       If the lights are off, skip this whole next part. (Simplified)
Zimmy, Feb 22 2012
  

       [marklar] nothing so clever, obsoive:
  

       ----8<---- 8<---snippety--8<---- 8<----8<------   

       boolean foundit = false;
  

       for (int x = 0; x < max_x; x++ ) {
if (searcharray[x] == findvalue) {
foundit = true;
break;}
}
if (foundit) {
PrintFunction("Found the result!");}
else { // i.e. didn't find it
PrintFunction("sadface");}
  

       -->8---->8---- >8----snip --->8---- >8---->8--   

       It is essentially doing what the idea suggests, only using existing syntax, rather than leaning on a new loop-specific construct.
zen_tom, Feb 22 2012
  

       bigsleep, Feb 15 2012   

       I like your idea of using "}broken{" and "}unbroken{" and "}finally{" block syntax. example:   

       for () { if () break; } broken { // activates if 'break' is used } unbroken{ // activates if 'break' is never used } finally { // clean up }   

       You mind if I make a separate half baked idea using that approach?   

       Also if the above approach is good, well is it a good idea to provide break with a 'return' flag? e.g. "break(flag1)" or "break 1" etc...
mofosyne, Feb 23 2012
  

       [zen_tom] if you replace "// i.e. didn't find it PrintFunction("sadface");}" with 200 lines of code with function calls and all manner of time-consuming crap in each loop, having the ability to break during any part of the loop might be desirable.   

       I'm really playing devil's advocate because as I said in my original comment, I can't see when it would be possible, unless you are doing something so time-consuming that the data has been changed during the loop by another process. But even then, checking variables external to the loop would take even more processing.   

       Actually, is this what happens when you check for database field locking?
marklar, Feb 23 2012
  

       But what would be the point of the "finally" construct? It just executes code whether or not the loop was broken, and after any resultant effects. How is that different from just having the code follow the loop?   

       Anyway, this whole thing is getting a bit silly, IMHO. The idea can be summed up as "allow postfix conditionals" and "have loops return a value", both of which, as I've pointed out above, are both already well known features of Ruby. So if your loop returns false on break, and non- false on successful completion (which is effectively the case with Ruby), the "broken" and "unbroken" constructs are then just synonyms for "||" and "&&", and you're simply using short-circuit evaluation to determine which one to run. Congratulations, you've just reinvented the ?: operator. Of course, since you can have break() return an arbitrary value in Ruby, you can pipe it to a case statement as above, and have an unlimited number of potential "cleanup" actions.   

       Seems to me that every part of this idea has already been implemented, and far more thoroughly at that, in at least one widely-used programming language. So what's new here?
ytk, Feb 23 2012
  
      
[annotate]
  


 

back: main index

business  computer  culture  fashion  food  halfbakery  home  other  product  public  science  sport  vehicle