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... Who uses it?

goto... Who uses it?

Scheduled Pinned Locked Moved The Lounge
questionlearning
131 Posts 66 Posters 6 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 Chris Maunder

    In SQL - fairly often to jump to the error handler at the end of our sprocs. I'll admit there's no good reason we do this, since it's easy enough for us to avoid this with if statements, but it's a pattern used in our original code and so for consistency we stuck with it:

    Create Procedure MyProc as

    Begin Tran
    
    -- Do stuff...
    
    if @@error <> 0 goto errorHandler
    
    Commit Tran
    Return 0
    

    errorHandler:
    Rollback Tran
    Return 1

    cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

    J Offline
    J Offline
    Jan Steyn
    wrote on last edited by
    #70

    An error condition returns the same value as a non-error condition? Many hamsters are dying because of that.

    C 1 Reply Last reply
    0
    • J Jan Steyn

      An error condition returns the same value as a non-error condition? Many hamsters are dying because of that.

      C Offline
      C Offline
      Chris Maunder
      wrote on last edited by
      #71

      Oops. Typo.

      cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

      1 Reply Last reply
      0
      • S Septimus Hedgehog

        Fortran IV made extensive use of them. I used to love them at the time. Since then, I've never used them. Perhaps they do have a use and if teams that write compilers put them in then whose to argue for and against?

        If there is one thing more dangerous than getting between a bear and her cubs it's getting between my wife and her chocolate.

        K Offline
        K Offline
        Kyudos
        wrote on last edited by
        #72

        Have you ever tried to "unuse" GOTO in optimized F77? The logic required to replicate the program flow without it is often horrendous and generally not worth the effort if the original code works...

        1 Reply Last reply
        0
        • D DanielSheets

          This isn't a programming question. Anyway... I find it useful in very few situations. It can make for cleaner code if used correctly. Of course, it can also be over used.

          Y Offline
          Y Offline
          YvesDaoust
          wrote on last edited by
          #73

          Blame has been put on the goto statement by a very famous article. In the old days of FORTRAN, with its old fashioned control statements, including conditional, assigned and computed goto's, or in early versions of the Basic language with its goto/gosub mechanisms, you had little other option to control the flow of execution than branching to numeric labels. Writing clean code was indeed a challenge, as it was hard to make the structure of the code apparent. Things have changed a lot thanks to structured languages so that pinches of goto's every here and there are quite acceptable, and possibly more advisable than some contortions used to avoid them at all costs. My favorite usage is when implementing state machines, every state being represented by a jump label and the decision-making block of code following it, which includes a number of explicit branches to other states. Such coding can involve tenths of goto's, while remaining crystal clear readable.

          1 Reply Last reply
          0
          • C Chris Maunder

            In SQL - fairly often to jump to the error handler at the end of our sprocs. I'll admit there's no good reason we do this, since it's easy enough for us to avoid this with if statements, but it's a pattern used in our original code and so for consistency we stuck with it:

            Create Procedure MyProc as

            Begin Tran
            
            -- Do stuff...
            
            if @@error <> 0 goto errorHandler
            
            Commit Tran
            Return 0
            

            errorHandler:
            Rollback Tran
            Return 1

            cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

            B Offline
            B Offline
            Brady Kelly
            wrote on last edited by
            #74

            Hasn't T-SQL had try-catch since 2005?

            1 Reply Last reply
            0
            • D DanielSheets

              This isn't a programming question. Anyway... I find it useful in very few situations. It can make for cleaner code if used correctly. Of course, it can also be over used.

              F Offline
              F Offline
              Fred Flams
              wrote on last edited by
              #75

              I'm still using GOTOs, not in my C# / JAVA / C++ code but in my SQL Code. It is still very usefull in SQL for error handling, MS introduced the BEGIN/END TRY/CATCH structure but it is not portable on version of SQL older than 2005 and it is absolutely not portable "as is" on another SQL Engine and most of the customers I've worked for have that mandatory requirement to be able to switch engine as they see fit (even if 90% of them will never take that step and stick to MS SQL Server).

              1 Reply Last reply
              0
              • D DanielSheets

                This isn't a programming question. Anyway... I find it useful in very few situations. It can make for cleaner code if used correctly. Of course, it can also be over used.

                T Offline
                T Offline
                Tieske8
                wrote on last edited by
                #76

                Goto is a perfectly well usable statement. It's been considered a bad practice from the times people tended to write spaghetti code by using only goto for flow control in their code. It is a tool, and if you use it right, it will help you write simple and maintainable code. But as with any tool, if you use it in a bad way, you get what you deserve. If I have nested code, if-then, several levels deep, I prefer goto. Much cleaner. Writing a function that throws the same exception in 10 places (example elsewhere in this discussion, with the critique he should have used exceptions) is more complex than the provided sample with the gotos (which I like). Could have done it myself. As a note; Lua 5.2 (released 2012) got the goto statement as a new enhancement to the language (so after 20 years of Lua)

                Cigarettes are a lot like hamsters. Perfectly harmless, until you put it in your mouth and light it on fire.

                1 Reply Last reply
                0
                • D DanielSheets

                  This isn't a programming question. Anyway... I find it useful in very few situations. It can make for cleaner code if used correctly. Of course, it can also be over used.

                  S Offline
                  S Offline
                  Super Lloyd
                  wrote on last edited by
                  #77

                  I am not afraid to say I used it at least 4 or 5 times! (in the last 10 years!...) Even once recently! I hate the mindless peer pressure against it, use it even it's ugly if you like! Use whatever makes your code more beautiful! ^^ Just so you know, the (mindless violent) hate against it is based on the following argument: "it's not maintainable" i.e. "it break the flow of the code which should be otherwise obvious" That much is true, long methods with goto label hidden 300 line below are big traps. But this is true of 300 lines method without goto too!!! So, shortly, use it if it's the shorter more expressive solution. If someone doesn't like it, suggest them to fix the code. And choose the most expressive readable code between theirs and yours after that! ;P Anyway, when one use goto? Err... truthfully only one C# exemple comes to my mind (apart switch): how to break out simple of multiple nest loop

                  for ()
                  for(..)
                  for(..)
                  {
                  if(condition)
                  goto exit_loop;
                  }
                  exit_loop:;

                  Just so you know, a typical C goto will be for clean up, as in

                  if (success1) {...}
                  else goto failure
                  If (sucess2) { ...}
                  goto failure
                  ...
                  return;
                  failure:

                  but in C# this is more nicely expressed with try {} catch {} finally {} which doesn't need any goto

                  My programming get away... The Blog... DirectX for WinRT/C# since 2013! Taking over the world since 1371!

                  A 1 Reply Last reply
                  0
                  • E emartinho

                    Wow. I expected more of a flame war. Bring on the rants!!!!

                    S Offline
                    S Offline
                    Super Lloyd
                    wrote on last edited by
                    #78

                    I hate all those anti-goto people! :mad:

                    My programming get away... The Blog... DirectX for WinRT/C# since 2013! Taking over the world since 1371!

                    R 1 Reply Last reply
                    0
                    • D dan sh

                      I beg to differ here. Check out the IL generated for the two methods:

                      void Test()
                      {
                      while (true)
                      {
                      string str = "Something";

                                  if (str.Length != 10)
                                  {
                                      continue;
                                  }
                      
                              }
                          }
                      
                          void Test2() {
                          x:
                              while (true)
                              {
                                  string str = "Something";
                      
                                  if (str.Length != 10)
                                  {
                                      goto x;
                                  }
                      
                              }
                          }
                      

                      //without GOTO .method private hidebysig instance void Test() cil managed { // Code size 32 (0x20) .maxstack 2 .locals init ([0] string str, [1] bool CS$4$0000) IL_0000: nop IL_0001: br.s IL_001c IL_0003: nop IL_0004: ldstr "Something" IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: callvirt instance int32 [mscorlib]System.String::get_Length() IL_0010: ldc.i4.s 10 IL_0012: ceq IL_0014: stloc.1 IL_0015: ldloc.1 IL_0016: brtrue.s IL_001b IL_0018: nop IL_0019: br.s IL_001c IL_001b: nop IL_001c: ldc.i4.1 IL_001d: stloc.1 IL_001e: br.s IL_0003 } // end of method Proof::Test //With GOTO .method private hidebysig instance void Test2() cil managed { // Code size 32 (0x20) .maxstack 2 .locals init ([0] string str, [1] bool CS$4$0000) IL_0000: nop IL_0001: br.s IL_001c IL_0003: nop IL_0004: ldstr "Something" IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: callvirt instance int32 [mscorlib]System.String::get_Length() IL_0010: ldc.i4.s 10 IL_0012: ceq IL_0014: stloc.1 IL_0015: ldloc.1 IL_0016: brtrue.s IL_001b IL_0018: nop IL_0019: br.s IL_0001 IL_001b: nop IL_001c: ldc.i4.1 IL_001d: stloc.1 IL_001e: br.s IL_0003 } // end of method Proof::Test2

                      "Bastards encourage idiots to use Oracle Forms, Web Forms, Access and a number of other dinky web publishing tolls.", Mycroft Holmes[^]

                      S Offline
                      S Offline
                      Super Lloyd
                      wrote on last edited by
                      #79

                      you're right, but bad example! ^^

                      void Test()
                      {
                      while (true)
                      {
                      string str = "Something";

                                  if (str.Length != 10)
                                  {
                                      continue;
                                  }
                                 blabla();
                      
                              }
                          }
                      
                          void Test2() {
                              while (true)
                              {
                                  string str = "Something";
                      
                                  if (str.Length != 10)
                                  {
                                      goto next;
                                  }
                                 blabla();
                      

                      next:;
                      }
                      }

                      My programming get away... The Blog... DirectX for WinRT/C# since 2013! Taking over the world since 1371!

                      1 Reply Last reply
                      0
                      • J John M Drescher

                        Honestly, I have written at least 1 million lines of code since I have used a goto. Although I do remember using a few gotos in the 1990s. Also long gone from my coding is writing x86 assembly code.

                        John

                        J Offline
                        J Offline
                        JohnLBevan
                        wrote on last edited by
                        #80

                        In my early days I used them a lot - then I discovered methods and functions and stopped using them. The only exceptions are certain languages which require goto (e.g. VBScript/VBA error handling - on error goto 0). In studying computer science I was also told that there was one valid known use of a goto statement, which was in a washing machine with an 8 bit processor where the use of the goto statement allowed for a saving on hardware costs. Sadly I can't remember the detail / can't find more info online.

                        1 Reply Last reply
                        0
                        • J Joe Woodbury

                          I would one step further since the ternary test is not only silly, it might throw an exception all on it's own due to text being null. If you KNOW something is "0", why parse it to 0? Why is an empty string valid? Is a null string valid? The code has other problems. Why create the file before you know whether there are any errors? Why set totalDelays and value back to zero? "its" is spelled "it's" in this context, but it should probably read "it was".

                          B Offline
                          B Offline
                          BobJanova
                          wrote on last edited by
                          #81

                          That ternary cannot throw. You're thinking of Java and its .equals nonsense. == won't throw for a null.

                          J 1 Reply Last reply
                          0
                          • D DanielSheets

                            This isn't a programming question. Anyway... I find it useful in very few situations. It can make for cleaner code if used correctly. Of course, it can also be over used.

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

                            DanielSheets wrote:

                            It can make for cleaner code if used correctly.

                            Post an example then, or it isn't so. I see you did, in another sub-thread, see my response there for a cleaner equivalent.

                            1 Reply Last reply
                            0
                            • D DanielSheets
                                  public static void SaveChartData(List dataList)
                                  {
                                      int totalDelays = 0;
                                      int value = 0;
                                      string errorString = "";
                                      // Use a temporary file in case there are any parse errors.
                                      string tmpFilePath = applicationPath + "TmpChartData.csv";
                                      using (StreamWriter sw = new StreamWriter(tmpFilePath))
                                      {
                                          foreach (DataGridClass dgc in dataList)
                                          {
                                              if (!int.TryParse((dgc.MATL.Equals("") ? "0" : dgc.MATL), out value))
                                              {
                                                  errorString = dgc.MATL;
                                                  goto ParseError;
                                              }
                                              totalDelays += value;
                                              if (!int.TryParse((dgc.EQUIP.Equals("") ? "0" : dgc.EQUIP), out value))
                                              {
                                                  errorString = dgc.EQUIP;
                                                  goto ParseError;
                                              }
                                              totalDelays += value;
                                              if (!int.TryParse((dgc.People.Equals("") ? "0" : dgc.People), out value))
                                              {
                                                  errorString = dgc.People;
                                                  goto ParseError;
                                              }
                                              totalDelays += value;
                                              if (!int.TryParse((dgc.Defects.Equals("") ? "0" : dgc.Defects), out value))
                                              {
                                                  errorString = dgc.Defects;
                                                  goto ParseError;
                                              }
                                              totalDelays += value;
                                              if (!int.TryParse((dgc.Other.Equals("") ? "0" : dgc.Other), out value))
                                              {
                                                  errorString = dgc.Other;
                                                  goto ParseError;
                                              }
                                              totalDelays += value;
                                              sw.WriteLine("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10}",
                                                  dgc.Year, dgc.Month, dgc.Goal, dgc.Completions, totalDelays, dgc.to,
                                                  dgc.MATL, dgc.EQUIP, dgc.People, dgc.Defects, dgc.Other);
                              
                                              totalDelays = 0;
                                              value = 0;
                                          }
                                      }
                                      // If we got this far then there were no parse errors.
                                      File.Copy(tmpFilePath, chartData, true);
                                      return;
                                  ParseError:
                                      string msg = string.Format("Unable to parse data. Verify its entered correctly.\\r\\nValue = {0}", errorString);
                                      MessageBox.Sho
                              
                              R Offline
                              R Offline
                              Rob Grainger
                              wrote on last edited by
                              #83

                              Quite simple, break the foreach loop into a separate method, returning a boolean. Replace goto's with return. Improved structure, documents itself (call it ParseDataGridList(List<DataGrid> dataList) ) Caller simply uses "if" on return value - if true { copies file } else { show message } Fixed.

                              1 Reply Last reply
                              0
                              • D DanielSheets

                                Where do you see UI code in the snippet I posted?

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

                                DataGridClass

                                1 Reply Last reply
                                0
                                • N Nemanja Trifunovic

                                  Real programmers (ones who code in languages like assembly, C and FORTRAN) use it all the time. Rest of us - rarely if ever.

                                  utf8-cpp

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

                                  Nemanja Trifunovic wrote:

                                  assembly, -C- and FORTRAN

                                  FTFY - rarely used in C either. (Edit - C with strikethrough looked too much like a Euro symbol)

                                  N 1 Reply Last reply
                                  0
                                  • H H Brydon

                                    dusty_dex wrote:

                                    Many a word has been written about the use of multiple exits being bad practice.

                                    I think I understand the issue from all sides and I don't drink that kool-aid. The way I look at it, the goto takes linear flow and folds it back on itself, causing the programmer to think about an interleaved mesh of logic instead of a stream. I see the following items as presenting different concepts and approve/disapprove of each on their own merits: (1) goto backwards within a loop (2) goto forwards within a loop (3) goto forwards to exit handler/error handler at end of method (4) break statement in a loop (4a) bounded loop (4b) infinite loop (ie. exit in the middle) (5) break statement in a switch() (6) continue statement in a loop (7) return statement inside a loop (one only per method) (8) multiple return statements in a method History has shown that #1 has caused the most problems, and #2 follows closely. #3 seems to be the one that most people defend, and I think it has some merit. I have used #3 but I still avoid it whenever I can. I regularly use all of #4 through #8 and have no problem with them. Multiple returns in a method are really no different from a break statement in terms of how the programmer's brain processes the logic. Multiple returns cause an exit from a method (so there is no tortured logic flow), you can debug it (eg. you can put a breakpoint on it), do not fold logic back (so that you can get to a statement from multiple directions) and can reduce the amount of code in a method (less code is better code). Probably other things too - this is off the top of my head.

                                    -- Harvey

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

                                    H.Brydon wrote:

                                    causing the programmer to think about an interleaved mesh of logic instead of a stream

                                    It also means that an optimiser is severely limited in the transformations it can make to code while retaining correctness - so will generally have a direct impact on performance too.

                                    1 Reply Last reply
                                    0
                                    • S Super Lloyd

                                      I hate all those anti-goto people! :mad:

                                      My programming get away... The Blog... DirectX for WinRT/C# since 2013! Taking over the world since 1371!

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

                                      That's OK, you're welcome to Goto Hell! ;-)

                                      1 Reply Last reply
                                      0
                                      • C C P User 3

                                        None dare mention the fact that "break" and "goto" are really the same thing

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

                                        No they are not. Break is designed to allow breaking out of a construct in a predictable, limited way. OK, in generated code, the result is still a branch, but one is much less likely to lead to abuses of control flow, particularly with later maintenance.

                                        C 1 Reply Last reply
                                        0
                                        • B BobJanova

                                          Isyourspacebarfaulty? 'Go to' is two words.

                                          M Offline
                                          M Offline
                                          MKJCP
                                          wrote on last edited by
                                          #89

                                          In FORTRAN the space is not required. It will work either way. That is odd in itself.

                                          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