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. goto statement

goto statement

Scheduled Pinned Locked Moved The Lounge
csharp
136 Posts 36 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.
  • T Tarek Elqusi

    Why many hate this statement and do not advise using it! I used it when I started programming with BASIC and GWBASIC. It is also found in the C#. Troubles are based on the programmer who is misusing it.

    B Offline
    B Offline
    Bill_Hallahan
    wrote on last edited by
    #31

    The book, "Classics In Software Engineering" has Dijkstra's excellent paper, "The Case Against The Goto". There was also another paper by another author in that book stating situations where the goto is useful. A goto is worthwhile in some very limited contexts. I found a related very short paper by Dijkstra online that is titled, "A Card Against The Goto" at http://www.cs.utexas.edu/users/EWD/transcriptions/EWD02xx/EWD215.html[^]. It is more of a philosophical outlook about the issue and doesn't go into the depth of the article in the book. It's also worthwhile reading the paragraphs under "Considered Harmful" at http://blogs.perl.org/users/erez_schatz/2011/07/rewriting-the-language.html[^]. That section tells about how when Dijkstra's article, "The Case Against The Goto" was submitted to the ACM magazine, the editor changed the title [to "Gotos Considered Harmful"] and created a furor! Two key sentences at the link above are: "It should cease to exist. Nothing in programming is definite. There is no single element that is either a silver bullet or the Antichrist." However, it is true that, in the vast majority of cases, using a goto can and should be avoided. But it's also a mistake to revile any code that contains a goto merely because the code contains one. By the way, I also agree with another poster that multiple returns in a function are undesirable, although I can see exceptions for this too. A single return in a function makes debugging so much easier. I make a serious effort to have only a single return, however, I have broken this guideline at times, particularly when working on critical legacy code where I wanted to minimize changes to the code. Here's a construct in pseudo-code that I've used in both C and C++ programs to avoid the need for gotos for multiple error cases. (By the way, I also always put the parenthesis in a statement, even for only one-line statements, because it makes the code easier to maintain. Typically, 85% of the cost, or time, spent on code is maintenance, so typically, code should be written to make it easy to maintain, as opposed to making

    F T 2 Replies Last reply
    0
    • B Bill_Hallahan

      The book, "Classics In Software Engineering" has Dijkstra's excellent paper, "The Case Against The Goto". There was also another paper by another author in that book stating situations where the goto is useful. A goto is worthwhile in some very limited contexts. I found a related very short paper by Dijkstra online that is titled, "A Card Against The Goto" at http://www.cs.utexas.edu/users/EWD/transcriptions/EWD02xx/EWD215.html[^]. It is more of a philosophical outlook about the issue and doesn't go into the depth of the article in the book. It's also worthwhile reading the paragraphs under "Considered Harmful" at http://blogs.perl.org/users/erez_schatz/2011/07/rewriting-the-language.html[^]. That section tells about how when Dijkstra's article, "The Case Against The Goto" was submitted to the ACM magazine, the editor changed the title [to "Gotos Considered Harmful"] and created a furor! Two key sentences at the link above are: "It should cease to exist. Nothing in programming is definite. There is no single element that is either a silver bullet or the Antichrist." However, it is true that, in the vast majority of cases, using a goto can and should be avoided. But it's also a mistake to revile any code that contains a goto merely because the code contains one. By the way, I also agree with another poster that multiple returns in a function are undesirable, although I can see exceptions for this too. A single return in a function makes debugging so much easier. I make a serious effort to have only a single return, however, I have broken this guideline at times, particularly when working on critical legacy code where I wanted to minimize changes to the code. Here's a construct in pseudo-code that I've used in both C and C++ programs to avoid the need for gotos for multiple error cases. (By the way, I also always put the parenthesis in a statement, even for only one-line statements, because it makes the code easier to maintain. Typically, 85% of the cost, or time, spent on code is maintenance, so typically, code should be written to make it easy to maintain, as opposed to making

      F Offline
      F Offline
      Forogar
      wrote on last edited by
      #32

      I prefer:

      // Some code here. Entering a section with lots of error checking.
      // Some code goes here that sets an error condition.
      if (!error)
      {
      // Some more code that sets an error condition.
      if (!error)
      {
      // Even more code that sets an error condition.
      if (!error)
      {
      // etc.
      }
      }
      }
      // The code continues here.

      No "do...while" required. This also has the advantage that excessive indenting reminds the programmer that they need to break the code out into method calls to simplify the layout. Once it gets past four or five indents this becomes obvious. Better would be:

      // Some code here. Entering a section with lots of error checking.
      // Some code goes here that sets an error condition.
      if (error)
      {
      // Report error details here.
      }
      else
      {
      // Some more code that sets an error condition.
      if (error)
      {
      // Report error details here.
      }
      else
      {
      // Even more code that sets an error condition.
      if (error)
      {
      // Report error details here.
      }
      else
      {
      // etc.
      }
      }
      }
      // The code continues here.

      This way each error can be reported as necessary, perhaps with some cleanup or roll-back code.

      - I would love to change the world, but they won’t give me the source code.

      B 1 Reply Last reply
      0
      • B Bill_Hallahan

        The book, "Classics In Software Engineering" has Dijkstra's excellent paper, "The Case Against The Goto". There was also another paper by another author in that book stating situations where the goto is useful. A goto is worthwhile in some very limited contexts. I found a related very short paper by Dijkstra online that is titled, "A Card Against The Goto" at http://www.cs.utexas.edu/users/EWD/transcriptions/EWD02xx/EWD215.html[^]. It is more of a philosophical outlook about the issue and doesn't go into the depth of the article in the book. It's also worthwhile reading the paragraphs under "Considered Harmful" at http://blogs.perl.org/users/erez_schatz/2011/07/rewriting-the-language.html[^]. That section tells about how when Dijkstra's article, "The Case Against The Goto" was submitted to the ACM magazine, the editor changed the title [to "Gotos Considered Harmful"] and created a furor! Two key sentences at the link above are: "It should cease to exist. Nothing in programming is definite. There is no single element that is either a silver bullet or the Antichrist." However, it is true that, in the vast majority of cases, using a goto can and should be avoided. But it's also a mistake to revile any code that contains a goto merely because the code contains one. By the way, I also agree with another poster that multiple returns in a function are undesirable, although I can see exceptions for this too. A single return in a function makes debugging so much easier. I make a serious effort to have only a single return, however, I have broken this guideline at times, particularly when working on critical legacy code where I wanted to minimize changes to the code. Here's a construct in pseudo-code that I've used in both C and C++ programs to avoid the need for gotos for multiple error cases. (By the way, I also always put the parenthesis in a statement, even for only one-line statements, because it makes the code easier to maintain. Typically, 85% of the cost, or time, spent on code is maintenance, so typically, code should be written to make it easy to maintain, as opposed to making

        T Offline
        T Offline
        Tarek Elqusi
        wrote on last edited by
        #33

        I remember that when I started learning programming in 1985 or before that the version of the language I started with was build with no loop statements, except the FOR loop. This made it relied heavily on GOTO statement in the case of conditional loops. I think for languages,if any, with such structure one HAVE to use it, with care.

        1 Reply Last reply
        0
        • F Forogar

          I prefer:

          // Some code here. Entering a section with lots of error checking.
          // Some code goes here that sets an error condition.
          if (!error)
          {
          // Some more code that sets an error condition.
          if (!error)
          {
          // Even more code that sets an error condition.
          if (!error)
          {
          // etc.
          }
          }
          }
          // The code continues here.

          No "do...while" required. This also has the advantage that excessive indenting reminds the programmer that they need to break the code out into method calls to simplify the layout. Once it gets past four or five indents this becomes obvious. Better would be:

          // Some code here. Entering a section with lots of error checking.
          // Some code goes here that sets an error condition.
          if (error)
          {
          // Report error details here.
          }
          else
          {
          // Some more code that sets an error condition.
          if (error)
          {
          // Report error details here.
          }
          else
          {
          // Even more code that sets an error condition.
          if (error)
          {
          // Report error details here.
          }
          else
          {
          // etc.
          }
          }
          }
          // The code continues here.

          This way each error can be reported as necessary, perhaps with some cleanup or roll-back code.

          - I would love to change the world, but they won’t give me the source code.

          B Offline
          B Offline
          Bill_Hallahan
          wrote on last edited by
          #34

          That code is you showed is fine, and I also prefer the the nested form of error checking when it is manageable. That isn't always the case. (Note the comment in my last message, there is no "silver bullet!") As I wrote in my code example, "That construct avoids the extreme indenting that can occur with a lot of nested error checks." The key words are "can" and "nesting". Deep nesting cannot always be easily avoided by breaking into functions, and when that is the case, the loop construct is useful. For the example below I used the nested form to compare 8 keys, where the values of the 8 keys form a single key to a dictionary (or a map). Each item in the map is sorted in lexicographic order. (This code snippet is taken from the article Generic Sparse Array and Sparse Matrices in C#[^]

              public int CompareTo(ComparableTuple8 group)
              {
                  int result = this.Item0.CompareTo(group.Item0);
          
                  if (result == 0)
                  {
                      result = this.Item1.CompareTo(group.Item1);
          
                      if (result == 0)
                      {
                          result = this.Item2.CompareTo(group.Item2);
          
                          if (result == 0)
                          {
                              result = this.Item3.CompareTo(group.Item3);
          
                              if (result == 0)
                              {
                                  result = this.Item4.CompareTo(group.Item4);
          
                                  if (result == 0)
                                  {
                                      result = this.Item5.CompareTo(group.Item5);
          
                                      if (result == 0)
                                      {
                                          result = this.Item6.CompareTo(group.Item6);
          
                                          if (result == 0)
                                          {
                                              result = this.Item7.CompareTo(group.Item7);
                                          }
                                      }
                                  }
                              }
                          }
                      }
                  }
          
                  return result;
              }
          
              #endregion
          }
          

          That is 8 keys.

          R 1 Reply Last reply
          0
          • F Forogar

            I always structure things to do validation at the top a bit like:

            private bool SomeMethod(string someStingArg, int anIntArg)
            {
            bool workedOK = false;
            if (IsValidForThisFunction(somString) && IsAlsoValid(anIntArg))
            {
            // Do stuff here...
            workedOK = true;
            }
            return workedOK;
            }

            ...or, if individual validations are necessary...

            private bool SomeMethod(string someStingArg, int anIntArg)
            {
            bool workedOK = false;
            if (IsValidForThisFunction(somString))
            {
            if (IsAlsoValid(anIntArg))
            {
            // Do stuff here...
            workedOK = true;
            }
            }
            return workedOK;
            }

            That way I still have only one exit - and I have all the validations at the top. Obviously there are try...catch blocks involved but I wanted to put a simple layout.

            - I would love to change the world, but they won’t give me the source code.

            Richard Andrew x64R Offline
            Richard Andrew x64R Offline
            Richard Andrew x64
            wrote on last edited by
            #35

            ERROR: Symbol "workedOK" is undefined in this context

            The difficult we do right away... ...the impossible takes slightly longer.

            F 1 Reply Last reply
            0
            • T Tarek Elqusi

              Why many hate this statement and do not advise using it! I used it when I started programming with BASIC and GWBASIC. It is also found in the C#. Troubles are based on the programmer who is misusing it.

              M Offline
              M Offline
              Marc Clifton
              wrote on last edited by
              #36

              I have never needed to use a GOTO statement in any language since BASIC. And when I wrote a recursive extension to the GOSUB function (along with a couple other snazzy enhancements) in Commodore PET's BASIC, I never needed one again either. Marc

              Day 1: Spider Database Navigator Unit Testing Succinctly

              1 Reply Last reply
              0
              • L Lost User

                That's fun too, but no - I mean the thing where they place the loops in a function and the goto turns into a return, and then they pretend that isn't really the same thing.

                J Offline
                J Offline
                Joe Woodbury
                wrote on last edited by
                #37

                Bur they aren't, and that's really the point. If all someone did was goto a label at the very end of a function, that would be ugly but not terribly problematic. The problem is that the goto ends up going to other logic. With many C developers, it was cleanup code (the destructors, so to speak) which wasn't so bad, but then someone would add more labels until you had a stack of exit conditions, sometimes intertwined. Then, inevitably, you'd find a goto from one scope to the middle of another and that's when you end up with really bad problems. EDIT: To be very clear, the problem with goto is not, and never really has been, with exiting a context abruptly, especially with RAII, but in entering another context at an arbitrarily point.

                1 Reply Last reply
                0
                • T Tarek Elqusi

                  Why many hate this statement and do not advise using it! I used it when I started programming with BASIC and GWBASIC. It is also found in the C#. Troubles are based on the programmer who is misusing it.

                  J Offline
                  J Offline
                  Joe Woodbury
                  wrote on last edited by
                  #38

                  I'll repeat an edit to my reply to Harold up above: The problem with goto is not, and never really has been, with exiting a context abruptly, especially with RAII, but in entering another context at an arbitrarily point.

                  1 Reply Last reply
                  0
                  • T Tarek Elqusi

                    Why many hate this statement and do not advise using it! I used it when I started programming with BASIC and GWBASIC. It is also found in the C#. Troubles are based on the programmer who is misusing it.

                    C Offline
                    C Offline
                    Christian Graus
                    wrote on last edited by
                    #39

                    Because it's so easy to misuse and because other constructs make it much easier to write readable code.

                    Christian Graus Driven to the arms of OSX by Vista. Read my blog to find out how I've worked around bugs in Microsoft tools and frameworks.

                    1 Reply Last reply
                    0
                    • Richard Andrew x64R Richard Andrew x64

                      ERROR: Symbol "workedOK" is undefined in this context

                      The difficult we do right away... ...the impossible takes slightly longer.

                      F Offline
                      F Offline
                      Forogar
                      wrote on last edited by
                      #40

                      It was typed in as an generic example (complete with typo), not compiled! :doh: :-D :-D :-D ..and now it's fixed so no-one will ever know!

                      - I would love to change the world, but they won’t give me the source code.

                      1 Reply Last reply
                      0
                      • T Tarek Elqusi

                        Why many hate this statement and do not advise using it! I used it when I started programming with BASIC and GWBASIC. It is also found in the C#. Troubles are based on the programmer who is misusing it.

                        M Offline
                        M Offline
                        Member 10088171
                        wrote on last edited by
                        #41

                        I use it and feel good when it is in my code because so many reputable sources are saying "do not do it" but not really showing any good reason why it is bad.

                        S 1 Reply Last reply
                        0
                        • T Tarek Elqusi

                          Why many hate this statement and do not advise using it! I used it when I started programming with BASIC and GWBASIC. It is also found in the C#. Troubles are based on the programmer who is misusing it.

                          L Offline
                          L Offline
                          Lost User
                          wrote on last edited by
                          #42

                          I agree. I love GOTO Use it all the time

                          int i = 0;
                          :beginLoop
                          if (foo[i] == searchTerm)
                          GOTO Found;
                          i+=1;
                          if i > foo.Length()
                          GOTO NotFound;
                          GOTO beginLoop;

                          :NotFound
                          MessageBox.Show("Not Found")';
                          GOTO ExitBad;

                          :Found
                          MessageBox.Show("Found one at " +i.ToString());
                          GOTO ExitGood;

                          :ExitBad
                          return false;

                          :ExitGood
                          return true;

                          What could be more clear and maintainable than that?

                          MVVM # - I did it My Way ___________________________________________ Man, you're a god. - walterhevedeich 26/05/2011 .\\axxx (That's an 'M')

                          T 1 Reply Last reply
                          0
                          • L Lost User

                            I agree. I love GOTO Use it all the time

                            int i = 0;
                            :beginLoop
                            if (foo[i] == searchTerm)
                            GOTO Found;
                            i+=1;
                            if i > foo.Length()
                            GOTO NotFound;
                            GOTO beginLoop;

                            :NotFound
                            MessageBox.Show("Not Found")';
                            GOTO ExitBad;

                            :Found
                            MessageBox.Show("Found one at " +i.ToString());
                            GOTO ExitGood;

                            :ExitBad
                            return false;

                            :ExitGood
                            return true;

                            What could be more clear and maintainable than that?

                            MVVM # - I did it My Way ___________________________________________ Man, you're a god. - walterhevedeich 26/05/2011 .\\axxx (That's an 'M')

                            T Offline
                            T Offline
                            Tarek Elqusi
                            wrote on last edited by
                            #43

                            :)

                            1 Reply Last reply
                            0
                            • P Pablo Aliskevicius

                              If you don't think that GOTO is an interesting topic of conversation, try the Duff device. http://www.lysator.liu.se/c/duffs-device.html[^]

                              Pablo. "Accident: An inevitable occurrence due to the action of immutable natural laws." (Ambrose Bierce, circa 1899). "You are to act in the light of experience as guided by intelligence" (Rex Stout, "In the Best Families", 1950).

                              A Offline
                              A Offline
                              altomaltes
                              wrote on last edited by
                              #44

                              Great page. I laught a lot. Seriouly talking. It's no easy to find pages with such a level of understanding the compiler works, but for me, fallout in the next case in switch statements without break is great. “My mother loved children -- she would have given anything if I had been one.” Grouch Marx.

                              1 Reply Last reply
                              0
                              • P PIEBALDconsult

                                altomaltes wrote:

                                your exit from work will be no too structured

                                That's an interrupt.

                                A Offline
                                A Offline
                                altomaltes
                                wrote on last edited by
                                #45

                                In C++ an exception, there is no return in that subrutine. The ANSI C equivalent may be a longjump, but this is even worst than a goto.

                                1 Reply Last reply
                                0
                                • T Tarek Elqusi

                                  Why many hate this statement and do not advise using it! I used it when I started programming with BASIC and GWBASIC. It is also found in the C#. Troubles are based on the programmer who is misusing it.

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

                                  On Error goto theCoffeeMachine;

                                  I use that one one-to-many times a day.

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

                                  1 Reply Last reply
                                  0
                                  • T Tarek Elqusi

                                    Why many hate this statement and do not advise using it! I used it when I started programming with BASIC and GWBASIC. It is also found in the C#. Troubles are based on the programmer who is misusing it.

                                    M Offline
                                    M Offline
                                    Mark H2
                                    wrote on last edited by
                                    #47

                                    It's right there in C++ as well....

                                    If your neighbours don't listen to The Ramones, turn it up real loud so they can. “We didn't have a positive song until we wrote 'Now I Wanna Sniff Some Glue!'” ― Dee Dee Ramone "The Democrats want my guns and the Republicans want my porno mags and I ain't giving up either" - Joey Ramone

                                    S 1 Reply Last reply
                                    0
                                    • T Tarek Elqusi

                                      Why many hate this statement and do not advise using it! I used it when I started programming with BASIC and GWBASIC. It is also found in the C#. Troubles are based on the programmer who is misusing it.

                                      J Offline
                                      J Offline
                                      jaybus56
                                      wrote on last edited by
                                      #48

                                      After far more than 20 years with C/C++ (and other languages too) I put it this way: I strongly recommend not using goto - except if it is really necessary. There should be no dogma but only good reasoning. There are good reasons for using a goto (most goto-s I've seen did not, but few did). In total I personally used it about maybe 10 times over all those years, but (as far as I see it) not breaking readability but guaranteeing readability at those perticular points. Of course it would have been possible to avoid the goto-s there too but only if I would have been breaking the "natural" logic of that code (or at least what seemed "natural" to me ;-)). Making a long talk short, I think: "There is no silver bullet".

                                      1 Reply Last reply
                                      0
                                      • G Gary R Wheeler

                                        OriginalGriff wrote:

                                        it needs a careful look at the whole of what is occurring and frequently a change of algorithm as well as hand-tuning of the code

                                        I've done some minor bits of optimization on occasion. I've never needed goto as part of any hand-tuning. Algorithm improvements and refactoring are generally the way to go for me.

                                        Software Zen: delete this;

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

                                        I second that. I've done lots of performance tuning, but it never required goto. At most, goto may improve the performance of the programmer who puts it into the code - but in the long run that "performance gain" will be lost in maintenance cost mmany times over!

                                        1 Reply Last reply
                                        0
                                        • L Lost User

                                          Under the hood almost every code block that is put into curly brackets is implemented with machine instructions for conditional or unconditional branches. GOTOs, if you want. They have just been hidden away. Unstructured spaghetti code is very hard to read and maintain. Readability and maintainability are even more important than correctness, at least in my book. Correctness will eventually follow as long as the code is readable. What I don't like is when people start religiously following rules and can even recite the reasons for them, often obviously without understanding the intentions behind them. 'Bad' code may have some other advantage than readability. If that advantage in a specific situation becomes more valuable than readability, then I would happily do what needs to be done. I also would heavily comment it to document my reasons for doing this. And the whole time I would enjoy the wailing of the code Nazis. :)

                                          Sent from my BatComputer via HAL 9000 and M5

                                          M Offline
                                          M Offline
                                          Mark H2
                                          wrote on last edited by
                                          #50

                                          CDP1802 wrote:

                                          Under the hood almost every code block that is put into curly brackets is implemented with machine instructions for conditional or unconditional branches. GOTOs, if you want. They have just been hidden away.

                                          I first cut my teeth on ICL System4 mainframes in 1979 and can still remember the conditional/unconditional branch instruction's machine code - 47 xx yy yy (I think JMP was it's assembler code mnemonic). XX was the condition, 0F was an unconditional branch. And YY YY was the prog address to go to. :) It's scary some of the completely useless info your brain retains.

                                          If your neighbours don't listen to The Ramones, turn it up real loud so they can. “We didn't have a positive song until we wrote 'Now I Wanna Sniff Some Glue!'” ― Dee Dee Ramone "The Democrats want my guns and the Republicans want my porno mags and I ain't giving up either" - Joey Ramone

                                          1 Reply 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