Tech Off Thread

59 posts

Jumping out of a heavily-nested loop not by using goto statement?

Back to Forum: Tech Off
  • User profile image
    The​Programmer

    Is there a way to jump of out a heavily-nested loop not by using goto statement? Since most people would agree that goto statement is evil, and it will easily destory a program's structure, so, I want to stay away from it. However, to my surprise, there is really no easy and effective way to jump out of a heavily-nested loop not by using it.



    Thanks

  • User profile image
    PhrostByte

    Goto is only evil if used incorrectly.  I have no problem using it to break out of a nested loop.  Actually it's the only place I would use it..

  • User profile image
    bitzero

    Hmm... lets think about this

    goto == bad programming
    heavily nested loop == far worse programming

    Don't use goto... fix your code!

  • User profile image
    GooberDLX

    no offense, but I agree with bitzero

    Smiley

    Jake

  • User profile image
    The​Programmer

    Well, if you've been programming for a while, you will know that at least 3-nested loop is a common practice:

    // in C/C++ and most other languages

    while()
    {
       for(;Wink{
          
           for(;Wink {
         
           }
       }

    }



    Java does not have goto statement at all, but in order to jump out of a several-nested loop, Java has a smart extended break statement, it works like this:

    first:{
      second:{
            third:{ 

             System.out.println("Before break.");
             if(condition) 
                  break second;
     
             System.out.println("This won't execute.");
         }
      }
      System.out.println("after second block.");
    }


    As we see, it does the job of breaking out of a loop, and it won't have the problem of goto statment which will easily destroy a program's structure. Jave really is a great language, if only it was a system language like C/C++.

    Unfortunately, C# does not have this smart label-break statement, and still continue supports goto. 


    I hope C# 2 will give us something like that. 



      
     

  • User profile image
    Tom Servo

    It doesn't AFAIK. Maybe C# 3.0.

  • User profile image
    AndyC

    TheProgrammer wrote:


    Unfortunately, C# does not have this smart label-break statement, and still continue supports goto. 


    I hope C# 2 will give us something like that. 
     


    I'd rather they didn't include it and got rid of goto.

    Both lead to messy, unreadable code and both can be avoided if you take time to structure the code better.

  • User profile image
    Rudi

    I'd say that you need to refactor your code, as in extract a method from one of the inner loops.

    That way it is easy to break out of the loop; just return; (Exit Sub/Function)

  • User profile image
    bitzero

    "Well, if you've been programming for a while, you will know that at least 3-nested loop is a common practice:"

    hmm.. NO...  I actually have been programming for a while - in fact I have for the last 10 years been employed in various places as a senior architect/mentor, to instruct and set coding policy across the enterprise..

    And I would shoot anyone who nested a loop under any circumstances - let alone three levels, and especially if you plan on exiting from it!

    Loops come in two forms : processing loops (ie for every value we want to do something)  - and search loops (we want to go through until we find something)

    Processing loops should always take the following form:

    f()                                 
    {                                   
       for (expression)                 
          g( value )                     
    }                                    

    And Search loops should always be

    f()                                 
    {                                   
       for (expression)                 
         if (condition)                  
            return value;               
       throw exception | return null    
    }                                   
     
    the only possible exception would be if you are doing some sort of computer graphics app, where I would tolerate a (for y) (for x) nesting, because the inner loop is likely to be quite simple and the structure makes more sense as an entirety.  That IS NOT the case if for instance you are adding a matrix of values to a grid, where it makes more readable sense to have an AddRow function which works on a single object.

    DON'T NEST LOOPS.   IT'S WRONG.

  • User profile image
    The​Programmer

    Well bitzero,

    Thank you for your reply. First, let get this straight, in the topic, I said ....not by using goto statement. I'm searching for an alternative style to code, since I really don't want to use use goto at all.

    Refactoring is one alternative method like Rudi said, and I will try to avoid nested loop, but I don't think it will be easy, but I will try my best.


    However, no one ever said nested loop is wrong, for example, I don't think you can produce the output result like this not by using nested loop:


    .
    . .
    . . .
    . . . .
    . . . . .
    . . . .
    . . .
    . .
    .


    Well, I'm not saying impossible, but if you know an alternative method, I would be interested. However, since you are more experienced than me, no doubt about it, would you share your thought.

    Thanks



  • User profile image
    bitzero

    printf(".\n..\n...\n....\n.....\n....\n...\n..\n.\n");

    ok - partially I'm being funny - but there is a point there too. There is always a better way.

  • User profile image
    cryoknight

    I think it's hilarious that so many programmers are afraid of goto.
    Sometimes they provide a very elegant way to handle a task,
    and I'm not just talking about breaking out of loops.
    You can also use them to replace your loops for optimization.
    I _think_ that was listed in "The Zen of Code Optimization" by
    Michael Abrash, but don't really recall the source.

    Goto is a tool.  It is not evil in itself...

    If you've ever programmed in assembler, you'd know that
    every comparison that you make results in a goto... (ie, jmp)


  • User profile image
    bitzero

    cryoknight: I used to program in assembler for years, in fact if you go to http://www.eskimo.com/~rwb/junk/prime.txt or download bmagic1b.zip - you'll see that I used to actually compete in it..

    and yet I'm scared of goto's

    why?

    We are using high-level languages that don't NEED them.  As you mention - every conditional, every looping construct we have results in a jump...  Which means we have lots of alternatives!

    I am not scared of goto's per se - I'm scared of the thinking that might lead a programmer using a high level language to use one - because neither structured thinking / oo thinking nor functional thinking can result in you concluding that you need one!  

    Goto's are wrong not because the underlying construct is flawed, but because we exist in a world now where process flow should be a structured hierarchy - where ALL complexity should be encapsulated in our class definitions, and where we have NO NEED for an explict reposition of the instruction pointer!

  • User profile image
    The​Programmer

    cryoknight wrote:
    I think it's hilarious that so many programmers are afraid of goto.


    TheProgrammer replies:

    50s-70s programmers love GOTO, then until 80s, they realized that GOTO was dangerous, and they began writing papers talking about how bad GOTO was. Some of the papers were read by Professors in Universities, some of them actually became Professors. 

    Then, 90s-20s programmers/future programmers are taught by those 50s-70s programmer Professors, and they are taught in a sense that GOTO is evil. 

    Me, being a 20s future programmer, are actually taught by those kind of Professors. To me, I will agree with them, for now. But think about it, they have more experience than us, we should listen to them. 

  • User profile image
    jsrfc58

    TheProgrammer wrote:
    cryoknight wrote:
    I think it's hilarious that so many programmers are afraid of goto.
     


    I think being afraid of goto is not only funny, but trying to turn everything into a class/object hierarchy is almost as extreme.  Things have to be taken on a case-by-case basis (although I have not used goto in over a decade).  The great thing about programming is that there are many solutions to the same problem...you could use a while loop, a for loop, a do-while loop, recursion, etc.  Each option has its own tradeoffs and faults.  Clarity of code, functionality and efficiency are far more important, however.  There are plenty of ways to lose people when you start using multiple inheritance like there is no tomorrow, or start putting in goto statements everywhere.

  • User profile image
    AndyC

    cryoknight wrote:

    Goto is a tool.  It is not evil in itself...

    If you've ever programmed in assembler, you'd know that
    every comparison that you make results in a goto... (ie, jmp)


    That's a totally different environment though, if your writing assembler you don't get the luxury of structured code.

    Goto's are evil. They make code difficult to follow (even when used very sparingly) and they tend to break a compilers ability to optimise the code (some compilers won't even try to optimise a function containing a goto)

  • User profile image
    amotif

    Rudi wrote:
    I'd say that you need to refactor your code, as in extract a method from one of the inner loops.

    That way it is easy to break out of the loop; just return; (Exit Sub/Function)


    That in itself doesn't solve the problem of control flow out of the inner loop.

    As I recall, the last time I used a goto in shipping production code was in a small parser written back in 1993 or 1994.  In C++, no less.  It was not evil.  It was easy to read and maintain.  I would defend its use in that code even today.  But I would prefer to have had Java's break label syntax available.

    Funny how people get religious about language features....

  • User profile image
    NeoZon

    static bool firstCondition = true;

    static bool secondCondition = true;

    static bool thirdcondition = ture;

     

     

    void iAmACarzyNestedLoop()

    {

    while(static.firstCondition))
    {

    while(static.secondCondition)

    {

                                                    while(static.thirdCondition)

    {

                                    if(condition)

    {

    IWantToICouldTurnOffThisThirdLoop(false);

                                                                    }

    }

    if(condition)

    {

    IWantToICouldTurnOffThisSecondLoop(false);

                                                    }

    if(condition)

    {

    IWantToICouldTurnOnThisThirdLoop(true);

                                                    }

    }

    if(condition)

    {

    IWantToICouldTurnOffThisFirstCondition(false);

                                    }

    if(condition)

    {

    IWantToICouldTurnOnThisSecondCondition(true);

                                    }

    if(condition)

    {

    IWantToICouldTurnOnThisThirdCondition(true);

                                    }

    }

    return 0;

    }
     

Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.