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.
  • F Fran Porretto

    Most of the first and second-generation languages were conceptually founded on some problem-oriented model. In focusing on a particular problem space, they tended to neglect other considerations. One result was that many languages were merely "assembler with better syntax" -- and the GOTO or branch instruction is impossible to do without in that scheme.

    Third-generation languages such as Algol and C began the move away from a hard problem orientation. They focused on other desiderata, such as structure and legibility. With the expansion in the variety of conditional and iterative control structures they offered, the GOTO became less necessary. That caused Dijkstra and others to study the relation between the GOTO and legible / comprehensible program design, and to reach the conclusion that the GOTO is harmful in the great majority of cases.

    All that having been said, there are still occasions when writing a GOTO is better practice than what it would take to avoid it. Indeed, some such cases involve using a GOTO to improve legibility and maintainability; transfer of control to a procedure's error handling exit is sometimes like that. However, it's best to be biased against GOTO, and to use it reluctantly, because 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.

    (This message is programming you in ways you cannot detect. Be afraid.)

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

    Fran Porretto wrote:

    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.

    Ooooh, I like that! Can I use it in my sig? ;)

    F 1 Reply Last reply
    0
    • S Stefan_Lang

      Fran Porretto wrote:

      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.

      Ooooh, I like that! Can I use it in my sig? ;)

      F Offline
      F Offline
      Fran Porretto
      wrote on last edited by
      #61

      (chuckle) Feel free. It was spontaneous, but the more I ponder it, the more accurate it seems!

      (This message is programming you in ways you cannot detect. Be afraid.)

      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.

        U Offline
        U Offline
        User 10363048
        wrote on last edited by
        #62

        Yes, I can agree that the goto statement can be confusing and I've never found a good use for it. However what is the difference between a goto and a exceptions? Exceptions are only suppose to be used for things that should never happen. Most of the time that I've seen them used for all error-handling methods. (E.G. Invalid user input) However I find throwing exceptions for this purpose, even with the performance hit, useful. It keeps the code cleaner and shows the next guy what I expect to happen. Just wondering what you thought? P.S. I once worked in a 4k memory space divided into 2 sections. The only way to get to the second memory space was with a goto statement.

        1 Reply Last reply
        0
        • OriginalGriffO OriginalGriff

          Because in nearly every case I have seen of it's use in C# or C++ it has been unnecessary, and only served to both confuse the code and show that the person who used it did not understand what he was doing. goto is not evil - but it is a "rule breaker" in that it violates all the principles of good code design and so using it should only be done with care. The problem is that it it taught on courses by lazy tutors as an easy way to get them started and then gets abused later because the students consider it "Normal" and don't learn to structure code well in the first place as a result. If you had grown up with GOTO as pretty much the only form of flow control (as I did) you would probably understand how easy it is to create impenetrable code with it, and why it should be discouraged until the coder is experienced enough to know when it is appropriate. About five years of "real" coding should be enough. But by then, he is probably experienced enough to know that there are probably better ways to achieve the same result...

          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.

          H Offline
          H Offline
          Herbie Mountjoy
          wrote on last edited by
          #63

          "Clever" use of GOTO can create macramé like code that is impossible to debug.

          I may not last forever but the mess I leave behind certainly will.

          K 1 Reply Last reply
          0
          • R Rob Grainger

            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 Offline
            B Offline
            Bill_Hallahan
            wrote on last edited by
            #64

            This is C# code, (although I have a SparseArray template for C++ article on codeproject). This code does look just like C++ though. The code was generated by a program. I had to create ComparableTuple generics for so many sizes, I wrote a program that generates the code. Still, I would want the code to be readable afterward. If you meant the code generator could use recursion, I agree, although the code I wrote uses iteration. I expect that is almost certainly what you meant. The run-time code shouldn't use recursion as that would be too inefficient, and this needs to be as fast as possible.

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

              G Offline
              G Offline
              gggustafson
              wrote on last edited by
              #65

              In 1974, my manager asked me to evaluate the new, highly touted discipline called "structured programming." I was skeptical. At that time, I was programming in COBOL. In those days, COBOL was somewhat deficient in the amount of control structures provided. I had not yet read Bohm and Jacopini so I had no idea that the control structures of COBOL were more than adequate for the task. I suggested that I wait to perform a structured programming experiment until a new project came along. In July, I was assigned a new project. The Chief of Naval Operations (CNO) Budget Office was in need of a text editor that could edit the descriptive portions of records in an indexed sequential file. The program would be developed and executed on a Unisys 1106 main frame computer. Unfortunately, the Budget Office also knew about the University of Maryland Text Editor (med) which, for all intents and purposes, replaced the Unisys provided editor (ed). The Budget Office wanted the interface to be "just like med" a seemingly impossible job for the short project time (three months). Fortunately, I found that med contained an API that would allow me to use the editor against the textual fields of the indexed sequential file. So it began. For this project I could not use a GOTO statement, a standard tool of the COBOL programmer of those days. I struggled with the problem. It wasn't that the solution was difficult; the solution was difficult without using GOTOs. Finally, in September, I finished. When queried by my manager, I told him that the programming effort took longer than it would have had I not used the structured programming paradigm. We agreed that, even though some rather impressive academians had suggested that structured programming was the way to go, we would shelve further use of the method. I placed the code listing in one of the drawers of my desk and returned to programming in my normal unstructured way. Then, in December, I received a call from the CNO production office. It appeared that a program that I had written had blown up. The production office provided the symptoms and the name of the program. I looked in my drawer and found the flawed program. When I opened the listing, I realized that this was the program that I had struggled with. As I reviewed the code, in light of the comments provided by the production office, the bug just seemed to jump from the page. It was such a simple error. But had I written the code in my normal manner, I would never have found the problem so quickly. After about fifte

              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.

                T Offline
                T Offline
                TNCaver
                wrote on last edited by
                #66

                OriginalGriff wrote:

                If you know what you are doing, then you have enough experience to know when it is appropriate to use.

                Yeah, but how do you know when you have enough experience to know when it's appropriate to use? :laugh: And then there's my sig...

                If you think 'goto' is evil, try writing an Assembly program without JMP.

                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.

                  V Offline
                  V Offline
                  vl2
                  wrote on last edited by
                  #67

                  Because they are ignorant idiots. Goto is absolutely essential in a number of cases. Most notable are: - Implementing state machines. The closest construction to state transition is goto, so it must be expressed as goto. - Various generated code (from higher level languages/DSLs)

                  W 1 Reply Last reply
                  0
                  • W werinus

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

                    V Offline
                    V Offline
                    vl2
                    wrote on last edited by
                    #68

                    You are so ignorant. Mind explaining, is the OCaml byte code interpreter really can be dismissed as an example of a "bad code"? Or you simply failed to think of this particular way of using goto?

                    W 1 Reply Last reply
                    0
                    • S Stefan_Lang

                      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 Offline
                      V Offline
                      vl2
                      wrote on last edited by
                      #69

                      Nearly all the static code analysis tools I know are operating on a CFG level (i.e., nothing but conditional and unconditional gotos). So, how exactly having an explicit goto may hinder code verification? And there are many benefits in using goto. Pity you failed to notice them in the past 30 years. Chances are, you never implemented a state machine or a threaded code interpreter, and you never generated code from a high level DSL.

                      S 1 Reply Last reply
                      0
                      • S Stefan_Lang

                        ... for backward compatibility only.

                        V Offline
                        V Offline
                        vl2
                        wrote on last edited by
                        #70

                        rgrep goto /path/to/linux/kernel/sources; git blame each of the hundreds of occurrences, and then try to convince those who committed that lines that they are worse coders than you are. Chances are, you're going to fail miserably.

                        1 Reply Last reply
                        0
                        • R Rob Grainger

                          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 Offline
                          V Offline
                          vl2
                          wrote on last edited by
                          #71

                          What? SSA transform is performed on a CFG, and it absolutely does not matter if there are irreducible sub-graphs in the flow. Not to mention a trivial fact that irreducible CFG can always be transformed into a reducible one by subgraph cloning.

                          R 1 Reply Last reply
                          0
                          • S Stefan_Lang

                            It's often hard to understand the reasons if all you do is look at the code you've just written. You have to "look" at the code that it will grow into after a year or more of maintaining and extending that code however! I've seen some huge 15-20 year old functions with several hundreds or even thousands of lines of code. After so many years, I could still guess the general shape and design of these functions when they were first written, and at that time, using goto was neither looked down upon quite as much, nor did it seem unreasonable in that particular piece of code. Over the years however, tons of features were added who required additional blocks of code; dozens of corner cases were detected that needed to be treated separately; and at least half a dozen developers added their differing visions of how the code should be formatted and designed. One of the things I tried over the years is split up that code into smaller, better maintainable chunks, but I've found there is no easy way to ensure this won't break the multitude of corner cases handled by this code. I could move some of it into initialization functions, and extract a few of the special feature code blocks. But it was nigh impossible to disentangle the mass of conditional code and goto statements (few as there were) while ensuring that the code would behave exactly like it did before. With none of the original programmers around to help determine what exactly the code was supposed to do, breaking it was too high a risk to take. I'm not saying that the goto statements were the sole reason for the sorry, unmaintainable state of the code, but they were the main reason why I was unable to transform it into something maintainable! tl;dr: If all you do is write short lived functions and programs then use goto at your hearts desire. But if that code that you're writing will go into a professional application that may live on and be maintained and exxtended for many years, then you better think ahead and don't introduce a legacy that is hard to bear and harder to kill!

                            V Offline
                            V Offline
                            vl2
                            wrote on last edited by
                            #72

                            Take a look at this decades old code - I bet you can easily read it: http://www.literateprogramming.com/adventure.pdf

                            S 1 Reply Last reply
                            0
                            • B Bill_Hallahan

                              This is C# code, (although I have a SparseArray template for C++ article on codeproject). This code does look just like C++ though. The code was generated by a program. I had to create ComparableTuple generics for so many sizes, I wrote a program that generates the code. Still, I would want the code to be readable afterward. If you meant the code generator could use recursion, I agree, although the code I wrote uses iteration. I expect that is almost certainly what you meant. The run-time code shouldn't use recursion as that would be too inefficient, and this needs to be as fast as possible.

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

                              No, I was not referring to runtime recursion you'll be pleased to know. That would be horrendously inefficient - and in my experience when you're writing code like this efficiency is often an issue. I am talking about code generation, but letting the compiler do the work for you using template metaprogramming. Modern C++ supports variadic templates, so a Tuple class can be declared something like:

                              template class Tuple : public Tuple
                              {
                              // ...
                              };

                              That is a tuple of any number of arguments, each of any type. Your CompareTo function can then be written using recursion that occurs entirely at compile-time. This does require a detailed knowledge of template meta-programming though, and is certainly beyond me explaining in a short response here. Luckily, the standard library already includes such a class named std::tuple. Here's a short example of its use:

                              #include #include int main()
                              {
                              auto t1 = std::make_tuple(1, 2, 3, 4, 5);
                              auto t2 = std::make_tuple(1, 2, 3, 4, 6);

                              if (t1 < t2)
                              	std::cout << "Less" << std::endl;
                              else if (t1 > t2)
                              	std::cout << "Greater" << std::endl;
                              else
                              	std::cout << "Equal" << std::endl;
                              
                              return 0;
                              

                              }

                              Given two tuples, this will actually generate at compile-time code more or less equivalent to the example you gave above. Indeed, given the two tuples defined above, a good compiler will simply realise that all the values are known at compile time, using Visual C++ 2013, I checked this. The program I just gave generates assembly that is equivalent to writing:

                              int main()
                              {
                              std::cout << "Less" << std::endl;
                              }

                              Sadly, you need to be using a really modern compiler for this goodness - VC++ just added support in 2013 - but it least its now supported by the most recent versions of all the major compilers. PS. If you really want to see the dirty details involved in this sort of metaprogramming let me know, it just may take me a bit longer to compose - I'm still finding my feet with this stuff myself.

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

                                Because in nearly every case I have seen of it's use in C# or C++ it has been unnecessary, and only served to both confuse the code and show that the person who used it did not understand what he was doing. goto is not evil - but it is a "rule breaker" in that it violates all the principles of good code design and so using it should only be done with care. The problem is that it it taught on courses by lazy tutors as an easy way to get them started and then gets abused later because the students consider it "Normal" and don't learn to structure code well in the first place as a result. If you had grown up with GOTO as pretty much the only form of flow control (as I did) you would probably understand how easy it is to create impenetrable code with it, and why it should be discouraged until the coder is experienced enough to know when it is appropriate. About five years of "real" coding should be enough. But by then, he is probably experienced enough to know that there are probably better ways to achieve the same result...

                                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.

                                K Offline
                                K Offline
                                KP Lee
                                wrote on last edited by
                                #74

                                OriginalGriff wrote:

                                it violates all the principles of good code design

                                Actually "good" code design is an evolving thing. When I started coding, spaghetti code was normal and "good" I much prefer today's standard of "good" and look forward to new definitions of good. Just read an article about how we should eliminate IF statements. Interesting, but you can see how the "IF" was encapsulated in the routine executed. But that is part of the new "good", encapsulate and re-use existing logic.

                                1 Reply Last reply
                                0
                                • H Herbie Mountjoy

                                  "Clever" use of GOTO can create macramé like code that is impossible to debug.

                                  I may not last forever but the mess I leave behind certainly will.

                                  K Offline
                                  K Offline
                                  KP Lee
                                  wrote on last edited by
                                  #75

                                  Herbie Mountjoy wrote:

                                  "Clever" use of GOTO...

                                  Not only difficult to debug, it makes it difficult to alter. I ran into code that had an if goto, code, if not goto, unlabeled code. I didn't dare change it by removing the code that would never get executed. I didn't know why the code was there or what it was supposed to do or if I missed something "clever" done.

                                  1 Reply Last reply
                                  0
                                  • R Rob Grainger

                                    No, I was not referring to runtime recursion you'll be pleased to know. That would be horrendously inefficient - and in my experience when you're writing code like this efficiency is often an issue. I am talking about code generation, but letting the compiler do the work for you using template metaprogramming. Modern C++ supports variadic templates, so a Tuple class can be declared something like:

                                    template class Tuple : public Tuple
                                    {
                                    // ...
                                    };

                                    That is a tuple of any number of arguments, each of any type. Your CompareTo function can then be written using recursion that occurs entirely at compile-time. This does require a detailed knowledge of template meta-programming though, and is certainly beyond me explaining in a short response here. Luckily, the standard library already includes such a class named std::tuple. Here's a short example of its use:

                                    #include #include int main()
                                    {
                                    auto t1 = std::make_tuple(1, 2, 3, 4, 5);
                                    auto t2 = std::make_tuple(1, 2, 3, 4, 6);

                                    if (t1 < t2)
                                    	std::cout << "Less" << std::endl;
                                    else if (t1 > t2)
                                    	std::cout << "Greater" << std::endl;
                                    else
                                    	std::cout << "Equal" << std::endl;
                                    
                                    return 0;
                                    

                                    }

                                    Given two tuples, this will actually generate at compile-time code more or less equivalent to the example you gave above. Indeed, given the two tuples defined above, a good compiler will simply realise that all the values are known at compile time, using Visual C++ 2013, I checked this. The program I just gave generates assembly that is equivalent to writing:

                                    int main()
                                    {
                                    std::cout << "Less" << std::endl;
                                    }

                                    Sadly, you need to be using a really modern compiler for this goodness - VC++ just added support in 2013 - but it least its now supported by the most recent versions of all the major compilers. PS. If you really want to see the dirty details involved in this sort of metaprogramming let me know, it just may take me a bit longer to compose - I'm still finding my feet with this stuff myself.

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

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

                                    I have read "Modern C++ Design" by Andrei Alexandrescu, which covers template metaprogramming in great detail. I use it, however, I don't use it when there is a simpler solution. In this case, the code is auto-generated by another program that writes the entire file. Also, the code I posted is written in C#, not C++.

                                    R 1 Reply Last reply
                                    0
                                    • S Stefan_Lang

                                      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.

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

                                      Stephan_Lang wrote: "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." Over the past 39 years, I've never used a goto in C or C++. I did use the goto in Basic. My first computer only had GWBasic and assembly language. Some situations where there is a benefit to a using goto are mentioned in Hopkin's 1979 paper, "A Case For The Goto", which I believe was written in response to Dijkstra's paper, "A Case Against The Goto". Even with modern compiler optimizations, the examples in both papers still apply today. I would, and have, gone to extreme lengths to avoid using a goto, for the reasons you mentioned. Even when I've had to jump out of the center of multiple nested loops, I used an exit-flag and an if-statement with a break after each loop. Still, there is no question that this is a bit slower than using a goto to jump out of the center. I have coded many real-time Digital Signal Processing algorithms with streaming data. Often these algorithms must be fast enough to keep up with the input data stream. In some cases, I have had to write special assembly code routines for some calculations, otherwise the algorithm couldn't keep up with the input data. Unfortunately, unlike the C language, assembly language isn't portable. Using a goto is likely to only result in a very small speed increase. I doubt that using a goto is typically justified, if it is ever justified. Still, there can be a benefit to using one, and I acknowledge that there might be some fringe case where, after other necessary algorithm and implementation optimizations have been done, using a goto is warranted. Thus I reject any dogmatic statement to the contrary. I say, as a general rule, use all possible techniques to avoid using a goto. I've always been able to avoid the goto. You can probably avoid the goto too. Check out one of the links in my first message in this thread where issue of dogma and the 'goto' is addressed. I also showed a loop construct as a way to avoid using a goto in some situations in that message.

                                      V S 2 Replies 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
                                        rx7man
                                        wrote on last edited by
                                        #78

                                        OK, from a relative novice, here's the way I see it, and pardon me, but I come from a Qbasic/VB background. As for multiple returns, if you have 10 conditions, lets say in a "Select case" statement, I see it OK to use multiple returns... if you have returns scattered, then I can see a problem. I find the following a neat way of doing this... I'm usually not much for the ":", but again I find that on something simple like this, putting the condition and the return value on the same line improves readability

                                        Select case i
                                        case 1 : return false
                                        case 2 : return true
                                        case 3 : return false
                                        end select

                                        T 1 Reply Last reply
                                        0
                                        • V vl2

                                          Nearly all the static code analysis tools I know are operating on a CFG level (i.e., nothing but conditional and unconditional gotos). So, how exactly having an explicit goto may hinder code verification? And there are many benefits in using goto. Pity you failed to notice them in the past 30 years. Chances are, you never implemented a state machine or a threaded code interpreter, and you never generated code from a high level DSL.

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

                                          Tools can only get you so far, and they're not suitable for prooving code correctness. So I'm not sure why you brought that up. As for benefits, I've read and taken part in countless discussions, and not a single example brought up managed to convince me. In every single case there was a suitable alternative using standard control statements. Most of the time the person bringing up either didn't come up with the proper way, or considered the effort of writing 2-5 additional lines of code too much to bear. Based on that experience I'm convinced that there is always a better alternative. People claiming otherwise are just not sufficiently experienced to see it, or understand the need. That said, all this assumes you're looking at code where proper coding guidelines and style even makes sense to take care of: if you're just programming away a piece of throw-away-code, then yes, use whatever suits you best and solves the problem. In actual production code that is going to live through years of maintenance and adding features, the presumed benefits of goto never outweigh the long term maintenance problems.

                                          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)

                                          V J 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