Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. Loop exit

Loop exit

Scheduled Pinned Locked Moved The Lounge
csharpc++javadelphialgorithms
53 Posts 24 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • C CBadger

    Since we are not burning the heretic yet... Are we talking about singapore[•] or the conference[○] :doh: For those not sure what they are reading now. This is most likely your face:bob: right about now

    »»» Loading Signature ««« · · · Please Wait · · ·    :badger:   :badger:   :badger:

    M Offline
    M Offline
    Mark_Wallace
    wrote on last edited by
    #14

    Certainly not the conference. Not one of the presentations is about the goto. They should be done for false advertising.

    I wanna be a eunuchs developer! Pass me a bread knife!

    C 1 Reply Last reply
    0
    • K kalberts

      Running into a feature-by-feature language comparison made me think back of a feature I saw in one single langugage, but would fit very nicely into a lot of the pascal/c/java/... class of languages: Alternate loop exits. When iterating through a list, an array or some sort of collection, objects are not all treated equally: You reach a sentinel, find the object you're searching for, reach the capacity of the bucket you are filling up, or whatever. The job has successfully been done, so you exit the loop. Or, you do not complete the job: There is no sentinel (because the buffer is completely filled), the desired object is not found, or the bucket has still some capacitly left. Running through the collection to the end or not running to the end are different situations, frequently requiring different handling. In most languages, an early exit requires that you set some boolean flag decleared outside the loop, then break (or whatever the keyword is in your favorite language), and after the loop you add an if-statement, syntactically detached from the loop, to provide differnt treatment based on the setting of the flag. I was programming in this language called Planc - "Programming LANguage for Nord Computers", a vendor specific systems implementation - remmebered by noone today. It had this nice syntactic sugar:

      for listpointer in listhead:nextfield do
      
        ... processing list element as desired
      
        while listpointer.keyvalue <> desidred\_key
      
        ... porcessing list element as desired
      
      exitwhile
        ... the desired list element was found, 
        write("list element was found and processed")
      
      exitfor 
        ... reached end of list without finding the desired element
        write("no element with the desired key was found in the list")
      
      endfor
      

      No need for any one-time-use bool cluttering up variable space. No need to introduce a separate block for testing and breaking out. No need for a detached if-statement - the different loop exit handling is syntactically integrated with the loop itself. I never saw this sort of construct in any other language, but I have been missing it hundred of times. Are there other languages out there with something similar? Certainly not C, C++, Java, C#, Pascal, ... And, by the way: The above specification of the iteration is a nice syntactic sugar for what would be in C-like languages:

      for (listptrtype listpointer = listhead; listpointer != null; listpointer =

      P Offline
      P Offline
      Pablo Aliskevicius
      wrote on last edited by
      #15

      What about this?

      foreach (x in someContainer)
      {
      ret = someFunction(x);
      }


      int someFunction(whatever x)
      {
      // do stuff
      if (someCondition) return 1;

      // do more stuff
      if (someOtherCondition) return 2;
      
      // ...
      return 3;
      

      }

      Is this close to what you meant, or did I miss the point?

      K D 2 Replies Last reply
      0
      • M Mark_Wallace

        As long as you do it quietly.

        I wanna be a eunuchs developer! Pass me a bread knife!

        B Offline
        B Offline
        Bergholt Stuttley Johnson
        wrote on last edited by
        #16

        humph

        You cant outrun the world, but there is no harm in getting a head start Real stupidity beats artificial intelligence every time.

        C 1 Reply Last reply
        0
        • P Pablo Aliskevicius

          What about this?

          foreach (x in someContainer)
          {
          ret = someFunction(x);
          }


          int someFunction(whatever x)
          {
          // do stuff
          if (someCondition) return 1;

          // do more stuff
          if (someOtherCondition) return 2;
          
          // ...
          return 3;
          

          }

          Is this close to what you meant, or did I miss the point?

          K Offline
          K Offline
          kalberts
          wrote on last edited by
          #17

          Still you must analyze those "ret" values, and values 1, 2, 3 do not syntactically convey the information that you reached the end of the collection (or skipped out of the loop). You need this extra "ret" value, which must be declared for this one-time use. While your proposal might be a starting point for explicitly coding what the compiler might generate, it certainly does not have the readability and syntactical clearness that the exitfor/exitwhile syntax has. Also, I doubt that the compiler would code it as a function. It would generate one jump label for the exitwhile clause, another for the exitfor (both defaulting to the first statement following the loop). The top line iteration test would jump to the exitfor label when the looping condition fails, the while statements would jump to the exitwhile label when it fails. If the language would provide block local program labels, visible only within the loop, I could code my example as

          for listpointer = listhead:nextfield do
          ...
          if listpointer.keyvalue = desired_key goto exitwhilelabel
          ...
          if listpointer.nextfield = null goto exitforlabel

          exitwhilelabel:
          ... object found
          goto endforlabel

          exitforlabel:
          ... object not found
          goto endforlabel

          endforlabel:
          endfor

          This is what a reaonable compiler would generate - but I think it ugly when written out in longhand code. Besides, jump labels do not have block local scope in any language I know of, so you would have to invent new labels for every loop using this mechanism ("if listpointer.keyvalue = desired_key goto exitwhilelabel117" - even more ugly!) I tried to make C macros that would generate unique labels, but the problem was to make the asocciation between the while part (or if test in the code above) and the appropriate exitwhile. A compiler could easily do this. (Tne "goto endforlabel" in the exitfor clause is redundant and would be optimized away, but it allows the exitfor and exitwhile clauses to be switched around.)

          1 Reply Last reply
          0
          • M Mark_Wallace

            Lookit, you might not actually type the word goto, but when you compile your code, every transition from one statement to another is translated into a goto.

            I wanna be a eunuchs developer! Pass me a bread knife!

            K Offline
            K Offline
            kalberts
            wrote on last edited by
            #18

            Mark_Wallace wrote:

            when you compile your code, every transition from one statement to another is translated into a goto.

            Assuming that the "another" statement is not the one immediately following.

            1 Reply Last reply
            0
            • M Mark_Wallace

              Shirley, using goto is simpler.

              I wanna be a eunuchs developer! Pass me a bread knife!

              K Offline
              K Offline
              kalberts
              wrote on last edited by
              #19

              Was your reply meant for another post? My name is not Shirley. Sure, my post was about flow control, and could compile into goto (/jump) instructions, they are certainly not The Answer in this case.

              1 Reply Last reply
              0
              • P Pablo Aliskevicius

                What about this?

                foreach (x in someContainer)
                {
                ret = someFunction(x);
                }


                int someFunction(whatever x)
                {
                // do stuff
                if (someCondition) return 1;

                // do more stuff
                if (someOtherCondition) return 2;
                
                // ...
                return 3;
                

                }

                Is this close to what you meant, or did I miss the point?

                D Offline
                D Offline
                Dan Neely
                wrote on last edited by
                #20

                I'd suggest an enum over magic numbers.

                Did you ever see history portrayed as an old man with a wise brow and pulseless heart, waging all things in the balance of reason? Is not rather the genius of history like an eternal, imploring maiden, full of fire, with a burning heart and flaming soul, humanly warm and humanly beautiful? --Zachris Topelius Training a telescope on one’s own belly button will only reveal lint. You like that? You go right on staring at it. I prefer looking at galaxies. -- Sarah Hoyt

                I 1 Reply Last reply
                0
                • B Bergholt Stuttley Johnson

                  burn the heretic, burn him I say

                  You cant outrun the world, but there is no harm in getting a head start Real stupidity beats artificial intelligence every time.

                  R Offline
                  R Offline
                  Ravi Bhavnani
                  wrote on last edited by
                  #21

                  Why?  Using a goto to exit a loop is one its few (perhaps only) valid use cases. /ravi

                  My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

                  S 1 Reply Last reply
                  0
                  • B Bergholt Stuttley Johnson

                    humph

                    You cant outrun the world, but there is no harm in getting a head start Real stupidity beats artificial intelligence every time.

                    C Offline
                    C Offline
                    CBadger
                    wrote on last edited by
                    #22

                    We don't need no water, let the ... :rolleyes:

                    »»» Loading Signature ««« · · · Please Wait · · ·    :badger:   :badger:   :badger:

                    1 Reply Last reply
                    0
                    • M Mycroft Holmes

                      Now I'm going to have to visit that place.

                      Never underestimate the power of human stupidity RAH

                      C Offline
                      C Offline
                      CBadger
                      wrote on last edited by
                      #23

                      You tell me :doh:

                      »»» Loading Signature ««« · · · Please Wait · · ·    :badger:   :badger:   :badger:

                      1 Reply Last reply
                      0
                      • M Mark_Wallace

                        Certainly not the conference. Not one of the presentations is about the goto. They should be done for false advertising.

                        I wanna be a eunuchs developer! Pass me a bread knife!

                        C Offline
                        C Offline
                        CBadger
                        wrote on last edited by
                        #24

                        Mark_Wallace wrote:

                        They should be done burned for false advertising.

                        :-\

                        »»» Loading Signature ««« · · · Please Wait · · ·    :badger:   :badger:   :badger:

                        1 Reply Last reply
                        0
                        • M Mark_Wallace

                          Shirley, using goto is simpler.

                          I wanna be a eunuchs developer! Pass me a bread knife!

                          R Offline
                          R Offline
                          Roger Wright
                          wrote on last edited by
                          #25

                          An elegant solution, Shirley! ;)

                          Will Rogers never met me.

                          M 1 Reply Last reply
                          0
                          • R Roger Wright

                            An elegant solution, Shirley! ;)

                            Will Rogers never met me.

                            M Offline
                            M Offline
                            Mark_Wallace
                            wrote on last edited by
                            #26

                            Why, thank you, Shirley. They say that elegance is simplicity, so I must be pretty elegant.

                            I wanna be a eunuchs developer! Pass me a bread knife!

                            1 Reply Last reply
                            0
                            • D Dan Neely

                              I'd suggest an enum over magic numbers.

                              Did you ever see history portrayed as an old man with a wise brow and pulseless heart, waging all things in the balance of reason? Is not rather the genius of history like an eternal, imploring maiden, full of fire, with a burning heart and flaming soul, humanly warm and humanly beautiful? --Zachris Topelius Training a telescope on one’s own belly button will only reveal lint. You like that? You go right on staring at it. I prefer looking at galaxies. -- Sarah Hoyt

                              I Offline
                              I Offline
                              irneb
                              wrote on last edited by
                              #27

                              :rolleyes: I like that ... for that matter, why loop at all? Just use goto and loose the while/for - just wear some flame retardant apparel. Actually, hang on, why even use goto? Why not copy-paste the code the required number of times instead of looping at all! Yeah! That's what Id do! :laugh:

                              1 Reply Last reply
                              0
                              • K kalberts

                                Running into a feature-by-feature language comparison made me think back of a feature I saw in one single langugage, but would fit very nicely into a lot of the pascal/c/java/... class of languages: Alternate loop exits. When iterating through a list, an array or some sort of collection, objects are not all treated equally: You reach a sentinel, find the object you're searching for, reach the capacity of the bucket you are filling up, or whatever. The job has successfully been done, so you exit the loop. Or, you do not complete the job: There is no sentinel (because the buffer is completely filled), the desired object is not found, or the bucket has still some capacitly left. Running through the collection to the end or not running to the end are different situations, frequently requiring different handling. In most languages, an early exit requires that you set some boolean flag decleared outside the loop, then break (or whatever the keyword is in your favorite language), and after the loop you add an if-statement, syntactically detached from the loop, to provide differnt treatment based on the setting of the flag. I was programming in this language called Planc - "Programming LANguage for Nord Computers", a vendor specific systems implementation - remmebered by noone today. It had this nice syntactic sugar:

                                for listpointer in listhead:nextfield do
                                
                                  ... processing list element as desired
                                
                                  while listpointer.keyvalue <> desidred\_key
                                
                                  ... porcessing list element as desired
                                
                                exitwhile
                                  ... the desired list element was found, 
                                  write("list element was found and processed")
                                
                                exitfor 
                                  ... reached end of list without finding the desired element
                                  write("no element with the desired key was found in the list")
                                
                                endfor
                                

                                No need for any one-time-use bool cluttering up variable space. No need to introduce a separate block for testing and breaking out. No need for a detached if-statement - the different loop exit handling is syntactically integrated with the loop itself. I never saw this sort of construct in any other language, but I have been missing it hundred of times. Are there other languages out there with something similar? Certainly not C, C++, Java, C#, Pascal, ... And, by the way: The above specification of the iteration is a nice syntactic sugar for what would be in C-like languages:

                                for (listptrtype listpointer = listhead; listpointer != null; listpointer =

                                S Offline
                                S Offline
                                Stefan_Lang
                                wrote on last edited by
                                #28

                                I haven't read all the responses that may or may not give a hint in that direction, but what exactly is it that these commands do that a break statement in C doesn't?

                                GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)

                                H 1 Reply Last reply
                                0
                                • S Stefan_Lang

                                  I haven't read all the responses that may or may not give a hint in that direction, but what exactly is it that these commands do that a break statement in C doesn't?

                                  GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)

                                  H Offline
                                  H Offline
                                  harvyk0
                                  wrote on last edited by
                                  #29

                                  Here is a real world example for you

                                  for (property = 0, len = obj.length; property < len; property++) {
                                  if (callback.call(obj[property], property, obj[property]) === false) {
                                  break;
                                  }
                                  }

                                  Once the following is true (callback.call(obj[property], property, obj[property]) === false), there is no point in continuing the loop, as a result the break will exit the loop. If the method has the answer it is looking for, you can also do

                                  for (property = 0, len = obj.length; property < len; property++) {
                                  if (callback.call(obj[property], property, obj[property]) === false) {
                                  return 1;
                                  }
                                  }

                                  so that not only will the loop end, but if there is nothing more in the method which will add value to the answer, the data is returned without needing to continue (bad choice of words, since continue has it's own special meaning) the loop and without needing to look at any more code.

                                  S 1 Reply Last reply
                                  0
                                  • H harvyk0

                                    Here is a real world example for you

                                    for (property = 0, len = obj.length; property < len; property++) {
                                    if (callback.call(obj[property], property, obj[property]) === false) {
                                    break;
                                    }
                                    }

                                    Once the following is true (callback.call(obj[property], property, obj[property]) === false), there is no point in continuing the loop, as a result the break will exit the loop. If the method has the answer it is looking for, you can also do

                                    for (property = 0, len = obj.length; property < len; property++) {
                                    if (callback.call(obj[property], property, obj[property]) === false) {
                                    return 1;
                                    }
                                    }

                                    so that not only will the loop end, but if there is nothing more in the method which will add value to the answer, the data is returned without needing to continue (bad choice of words, since continue has it's own special meaning) the loop and without needing to look at any more code.

                                    S Offline
                                    S Offline
                                    Stefan_Lang
                                    wrote on last edited by
                                    #30

                                    That wasn't my question at all. I know what break does. And exactly because I understand what it does, I do not understand the original question! I don't know Planc, but from the original posting my understanding was that the commands pointed out there - exitfor, exitwhile - simply exit from the loop. Just like break does. I don't see the difference, and therefore I don't see the point of the question.

                                    GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)

                                    L 1 Reply Last reply
                                    0
                                    • M Mark_Wallace

                                      Shirley, using goto is simpler.

                                      I wanna be a eunuchs developer! Pass me a bread knife!

                                      S Offline
                                      S Offline
                                      Simon ORiordan from UK
                                      wrote on last edited by
                                      #31

                                      Goto the cockpit and see what the hold up is. And don't call me Shirley.

                                      1 Reply Last reply
                                      0
                                      • R Ravi Bhavnani

                                        Why?  Using a goto to exit a loop is one its few (perhaps only) valid use cases. /ravi

                                        My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

                                        S Offline
                                        S Offline
                                        SortaCore
                                        wrote on last edited by
                                        #32

                                        I've been known to use it for "load variable amounts of stuff from DB as needed" and use goto to get to the cleanup/UI enabling at the end. It probably comes from the habit of preferring:

                                        void someFunc()
                                        {
                                        if (!A)
                                        return;
                                        DoStuffWithA()
                                        DoMoreCrud();
                                        }

                                        rather than

                                        void someFunc()
                                        {
                                        if (A)
                                        {
                                        DoStuffWithA();
                                        DoMoreCrud();
                                        }
                                        }
                                        // TWO close braces with no code between? Surely you jest.

                                        1 Reply Last reply
                                        0
                                        • S Stefan_Lang

                                          That wasn't my question at all. I know what break does. And exactly because I understand what it does, I do not understand the original question! I don't know Planc, but from the original posting my understanding was that the commands pointed out there - exitfor, exitwhile - simply exit from the loop. Just like break does. I don't see the difference, and therefore I don't see the point of the question.

                                          GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)

                                          L Offline
                                          L Offline
                                          L Braun
                                          wrote on last edited by
                                          #33

                                          After a loop, how do you know if you finished it or breaked out of it? This post is not about just leaving a loop, but about knowing how you left it and act according it. We probably all know how to do that in c, but this is about a language that adds syntax elements for that.

                                          M S 2 Replies Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups