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.

    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
                            • OriginalGriffO OriginalGriff

                              If you know what you are doing, then you have enough experience to know when it is appropriate to use. I completely agree with you: it's a useful tool. But like all tools, you have to know how and when to use it. Performance tuning (as you know well) needs more than just "quick code" - 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. And if you know what you are doing enough to do that, you understand the effects of your changes. Even Dijkstra said that it has it's place, but that use must be tempered with knowledge of the effects. Obligatory XKCD reference[^]

                              The only instant messaging I do involves my middle finger. English doesn't borrow from other languages. English follows other languages down dark alleys, knocks them over and goes through their pockets for loose grammar.

                              R Offline
                              R Offline
                              Rob Grainger
                              wrote on last edited by
                              #51

                              Another big consideration is use of goto's will frequently severely hamper of the ability of your compiler to optimise code - without the application knowledge, it can rarely make safe assumptions in their presence and it messes up the SSA (Static Single Assignment) style optimisations by complicating the control flow graph. So while you may be able to think of it at as optimisation, it may prevent the compiler doing so. It's also not high on the list of things they feel they should concentrate on, so I wouldn't count on big improvements soon.

                              "If you don't fail at least 90 percent of the time, you're not aiming high enough." Alan Kay.

                              V 1 Reply Last reply
                              0
                              • F Forogar

                                After using FORTRAN for far too long (up to Fortran-77) with it's use of GOTO and, even more obfuscating, computed gotos, I started using C. However, I was self-taught and was therefore never was taught by anybody that there was a GOTO in the language! I used C for several years, then C++ and now I am firmly in the C# camp. I personally have never used GOTO in any of that code and was shocked one day to find a GOTO residing in someone else's code I had to fix. It was a revelation as big as finding out that one is allowed to use guns during a penalty kick-off. I didn't even know the syntax existed! The whole point of my argument is that I never felt the need for a GOTO at any time, ever - so I didn't miss it. I didn't make artificial constructs to get around using GOTO; I didn't deliberately re-write my code to avoid using one; it just came about naturally that I didn't ever need one. Having said that, I am sure that GOTO may be useful in some real-time code somewhere for performance reasons. My real bug-bear is with multiple RETURNs. I do actually go out of my way to avoid them and re-write them out of existence wherever I find them. I have not yet found any instance where multiple RETURNs from a method has been necessary. I miss allowing the drop through of CASE statements in a switch that has been removed in C#, forcing me to put BREAK at the end of each part and leading me to repeat code unnecessarily now and then so I am not always in favour of compiler/syntax restrictions in a language but I wish multiple RETURNs had been proscribed in the same way.

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

                                R Offline
                                R Offline
                                Rob Grainger
                                wrote on last edited by
                                #52

                                I think that multiple return advice is not longer necessary in modern C++ - simply use RAII style techniques, and you are guaranteed correct cleanup at exit. (Still shouldn't be overrused though)

                                "If you don't fail at least 90 percent of the time, you're not aiming high enough." Alan Kay.

                                1 Reply Last reply
                                0
                                • B Bill_Hallahan

                                  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 Offline
                                  R Offline
                                  Rob Grainger
                                  wrote on last edited by
                                  #53

                                  Examples like this really make the advantages of C++'s templates apparent. That could all be done by recursion - evaluated at compile-time, and be generalised to any N-tuple. It also makes the advantage of RAII apparent - use multiple returns safely with the guarantee of deterministic cleanup.

                                  "If you don't fail at least 90 percent of the time, you're not aiming high enough." Alan Kay.

                                  B 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.

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

                                    1. If it is critical that your code is correct, don't use goto: it has the capability to jump out of or into one or more nesting layers - even backwards - and thus makes it considerably harder to verify the correctness of the code. 2. If there is more than one programmer on the team, don't use goto: using it makes it considerably harder for another programmer to understand the flow of code, and what it is supposed to do. 3. If you intend to build on and maintain the code over a period of more than a couple of months, don't use goto: viewing a piece of code that you yourself wrote a couple of months ago is often not so much different from viewing another programmers' code - see item 2 above. Please note that modern programming languages have plenty of alternatives that can be used in many cases where goto could be used. In C/C++, here are some examples: - to repeat a block of code, use a for, while, or do loop construct rather than jumping backwards - to skip over some piece of code, use an if-block rather than jumping forward - to skip over the rest of a loop body, use continue - to exit out of a loop, use break In C++ you should also use the standard exception handling mechanism rather than using goto as an error exit mechanism. (There is no equivalent in C, so you might argue that in C the use of goto for that purpose is acceptable - but see below!) The main reason however that you shouldn't use goto is that there is no benefit. Over the past 30 years I've used, learned about, read about, and had plenty of discussions about goto. In all that time I've never heard or read one compelling argument in favor of using it. Yes, you can use it to reduce or avoid nesting, or otherwise reduce the amount of code. But that by itself is not a valid argument in my book.

                                    V B 2 Replies Last reply
                                    0
                                    • M Mark H2

                                      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 Offline
                                      S Offline
                                      Stefan_Lang
                                      wrote on last edited by
                                      #55

                                      ... for backward compatibility only.

                                      V 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
                                        Mardy Git
                                        wrote on last edited by
                                        #56

                                        Remember

                                        goto

                                        is a four letter word and bad things will happen if you use it...

                                        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.

                                          W Offline
                                          W Offline
                                          werinus
                                          wrote on last edited by
                                          #57

                                          No. Simple as that. the only reason to use goto is to write bad code :)

                                          V 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