<p>Everyone is aware of Dijkstra's <a href="http://portal.acm.org/citation.cfm?doid=362947" rel="noreferrer">Letters to the editor: go to statement considered harmful</a> (also <a href="http://www.cs.utexas.edu/%7EEWD/transcriptions/EWD02xx/EWD215.html" rel="noreferrer">here</a> .html transcript and <a href="http://www.cs.utexas.edu/users/EWD/ewd02xx/EWD215.PDF" rel="noreferrer">here</a> .pdf) and there has been a formidable push since that time to eschew the goto statement whenever possible. While it's possible to use goto to produce unmaintainable, sprawling code, it nevertheless remains in <a href="http://msdn.microsoft.com/en-us/library/13940fs2(VS.71).aspx" rel="noreferrer">modern programming languages</a>. Even the advanced <a href="http://en.wikipedia.org/wiki/Goto#Continuations" rel="noreferrer">continuation</a> control structure in Scheme can be described as a sophisticated goto.</p>
<p>What circumstances warrant the use of goto? When is it best to avoid?</p>
<p>As a follow-up question: C provides a pair of functions, setjmp() and longjmp(), that provide the ability to goto not just within the current stack frame but within any of the calling frames. Should these be considered as dangerous as goto? More dangerous?</p>
<hr />
<p>Dijkstra himself regretted that title, for which he was not responsible. At the end of <a href="http://www.cs.utexas.edu/%7EEWD/transcriptions/EWD13xx/EWD1308.html" rel="noreferrer">EWD1308</a> (also <a href="http://www.cs.utexas.edu/%7EEWD/ewd13xx/EWD1308.PDF" rel="noreferrer">here</a> .pdf) he wrote:</p>
<blockquote>
<p>Finally a short story for the record.
In 1968, the Communications of the ACM
published a text of mine under the
title &quot;<em>The goto statement considered
harmful</em>&quot;, which in later years would
be most frequently referenced,
regrettably, however, often by authors
who had seen no more of it than its
title, which became a cornerstone of
my fame by becoming a template: we
would see all sorts of articles under
the title &quot;X considered harmful&quot; for
almost any X, including one titled
&quot;Dijkstra considered harmful&quot;. But
what had happened? I had submitted a
paper under the title &quot;<em><strong>A case against
the goto statement</strong></em>&quot;, which, in order
to speed up its publication, the
editor had changed into a &quot;letter to
the Editor&quot;, and in the process he had
given it a new title of his own
invention! The editor was Niklaus
Wirth.</p>
</blockquote>
<p>A well thought out classic paper about this topic, to be matched to that of Dijkstra, is <a href="http://www.clifford.at/cfun/cliffdev/p261-knuth.pdf" rel="noreferrer">Structured Programming with go to Statements</a>, by Donald E. Knuth. Reading both helps to reestablish context and a non-dogmatic understanding of the subject. In this paper, Dijkstra's opinion on this case is reported and is even more strong:</p>
<blockquote>
<p><em>Donald E. Knuth:</em> I believe that by presenting such a
view I am not in fact disagreeing
sharply with Dijkstra's ideas, since
he recently wrote the following:
&quot;Please don't fall into the trap of
believing that I am terribly
dogmatical about [the go to
statement]. <strong>I have the uncomfortable
feeling that others are making a
religion out of it, as if the
conceptual problems of programming
could be solved by a single trick, by
a simple form of coding discipline!</strong>&quot;</p>
</blockquote>

[{'answer_id': 46597, 'author': 'John Millikin', 'author_id': 3560, 'author_profile': 'https://Stackoverflow.com/users/3560', 'pm_score': 3, 'selected': False, 'text': '<p>The original paper should be thought of as "Unconditional GOTO Considered Harmful". It was in particular advocating a form of programming based on conditional (<code>if</code>) and iterative (<code>while</code>) constructs, rather than the test-and-jump common to early code. <code>goto</code> is still useful in some languages or circumstances, where no appropriate control structure exists.</p>\n'}, {'answer_id': 46599, 'author': 'Brian R. Bondy', 'author_id': 3153, 'author_profile': 'https://Stackoverflow.com/users/3153', 'pm_score': 2, 'selected': False, 'text': '<p>You can use it for breaking from a deeply nested loop, but most of the time your code can be refactored to be cleaner without deeply nested loops. </p>\n'}, {'answer_id': 46635, 'author': 'Lasse V. Karlsen', 'author_id': 267, 'author_profile': 'https://Stackoverflow.com/users/267', 'pm_score': 4, 'selected': False, 'text': "<p>There is no such things as <em>GOTO considered harmful</em>.</p>\n\n<p>GOTO is a tool, and as all tools, it can be used and <em>abused</em>.</p>\n\n<p>There are, however, many tools in the programming world that have a tendency to be <em>abused</em> more than being <em>used</em>, and GOTO is one of them. the <em>WITH</em> statement of Delphi is another.</p>\n\n<p>Personally I don't use either <em>in typical code</em>, but I've had the odd usage of both <em>GOTO</em> and <em>WITH</em> that were warranted, and an alternative solution would've contained more code.</p>\n\n<p>The best solution would be for the compiler to just warn you that the keyword was <em>tainted</em>, and you'd have to stuff a couple of pragma directives around the statement to get rid of the warnings.</p>\n\n<p>It's like telling your kids to <em>not run with scissors</em>. Scissors are not bad, but some usage of them are perhaps not the best way to keep your health.</p>\n"}, {'answer_id': 46638, 'author': 'Rob Walker', 'author_id': 3631, 'author_profile': 'https://Stackoverflow.com/users/3631', 'pm_score': 7, 'selected': False, 'text': '<p>Sometimes it is valid to use GOTO as an alternative to exception handling within a single function:</p>\n<pre class="lang-c prettyprint-override"><code>    if (f() == false) goto err_cleanup;\n    if (g() == false) goto err_cleanup;\n    if (h() == false) goto err_cleanup;\n    \n    return;\n    \n    err_cleanup:\n    ...\n</code></pre>\n<p>COM code seems to fall into this pattern fairly often.</p>\n'}, {'answer_id': 46658, 'author': 'Brian Leahy', 'author_id': 580, 'author_profile': 'https://Stackoverflow.com/users/580', 'pm_score': 3, 'selected': False, 'text': '<p>One modern GOTO usage is by the C# compiler to create state machines for enumerators defined by yield return.</p>\n\n<p>GOTO is something that should be used by compilers and not programmers.</p>\n'}, {'answer_id': 46661, 'author': 'DevelopingChris', 'author_id': 1220, 'author_profile': 'https://Stackoverflow.com/users/1220', 'pm_score': 2, 'selected': False, 'text': '<p>GOTO is like a table saw, extremely useful when appropriate safety measures are taken.</p>\n\n<p>I consider it harmful, because most beginners lose fingers with both table saws, and GOTOs.</p>\n\n<p>There are some situations where its the only way to control flow, but those situations can be avoided.</p>\n'}, {'answer_id': 46665, 'author': 'Christian Oudard', 'author_id': 3757, 'author_profile': 'https://Stackoverflow.com/users/3757', 'pm_score': 0, 'selected': False, 'text': '<p>The basic idea is that goto gives you too much freedom to do something you didn\'t intend to. It can cause errors in places that don\'t appear to be related to the goto statement, so it makes code maintenance more difficult. If you think you need a goto statement, you\'re wrong :) and you should instead rethink your code construction. This is why modern programming languages have put alot of effort into giving you readable, maintainable flow control constructs, and exception handling mechanisms.</p>\n\n<p>I\'m also going to disagree with lassevk. Since goto is abused more than correctly used, I believe it has no place in a well designed language. Even for goto\'s "ideal" uses, the other ways of doing it which require more code should be preferred.</p>\n\n<p>So in summary, yes it is still considered harmful.</p>\n'}, {'answer_id': 46732, 'author': 'Adam Davis', 'author_id': 2915, 'author_profile': 'https://Stackoverflow.com/users/2915', 'pm_score': 3, 'selected': False, 'text': "<p>About the only place I agree Goto <em>could</em> be used is when you need to deal with errors, and each particular point an error occurs requires special handling.</p>\n\n<p>For instance, if you're grabbing resources and using semaphores or mutexes, you have to grab them in order and you should always release them in the opposite manner.</p>\n\n<p>Some code requires a very odd pattern of grabbing these resources, and you can't just write an easily maintained and understood control structure to correctly handle both the grabbing and releasing of these resources to avoid deadlock.</p>\n\n<p>It's always possible to do it right without goto, but in this case and a few others Goto is actually the better solution primarily for readability and maintainability.</p>\n\n<p>-Adam</p>\n"}, {'answer_id': 46789, 'author': 'Jim McKeeth', 'author_id': 255, 'author_profile': 'https://Stackoverflow.com/users/255', 'pm_score': 8, 'selected': False, 'text': '<p><a href="http://xkcd.com/292/" rel="noreferrer"><img src="https://i.stack.imgur.com/6C1F5.png" alt="XKCD&#39;s GOTO Comic" title="Neal Stephenson thinks it&#39;s cute to name his labels &#39;dengo&#39;"></a></p>\n\n<p>A coworker of mine said the only reason to use a GOTO is if you programmed yourself so far into a corner that it is the only way out.  In other words, proper design ahead of time and you won\'t need to use a GOTO later.  </p>\n\n<p>I thought this comic illustrates that beautifully "I could restructure the program\'s flow, or use one little \'GOTO\' instead."  A GOTO is a weak way out when you have weak design.  <em>Velociraptors prey on the weak</em>.  </p>\n'}, {'answer_id': 46809, 'author': 'Aardvark', 'author_id': 3655, 'author_profile': 'https://Stackoverflow.com/users/3655', 'pm_score': 2, 'selected': False, 'text': "<p>I avoid it since a coworker/manager will undoubtedly question its use either in a code review or when they stumble across it. While I think it has uses (the error handling case for example) - you'll run afoul of some other developer who will have some type of problem with it. </p>\n\n<p>It’s not worth it.</p>\n"}, {'answer_id': 46852, 'author': 'bruceatk', 'author_id': 791, 'author_profile': 'https://Stackoverflow.com/users/791', 'pm_score': 1, 'selected': False, 'text': '<p>I only have the need for it in Basic (ie. VB, VBScript, etc.) and batch files.  I then only use it for error handling.  In Basic I tend only use the "on error goto".  In batch files I have to use it because there isn\'t an else command.  I then only use them as forward jumps to meaningful labels.</p>\n'}, {'answer_id': 47461, 'author': 'Marcio Aguiar', 'author_id': 4213, 'author_profile': 'https://Stackoverflow.com/users/4213', 'pm_score': 6, 'selected': False, 'text': '<p>In <a href="http://web.archive.org/web/20130521051957/http://kerneltrap.org/node/553/2131" rel="noreferrer">Linux: Using goto In Kernel Code</a> on Kernel Trap, there\'s a discussion with Linus Torvalds and a "new guy" about the use of GOTOs in Linux code. There are some very good points there and Linus dressed in that usual arrogance :)</p>\n\n<p>Some passages:</p>\n\n<blockquote>\n  <p>Linus: "No, you\'ve been brainwashed by\n  CS people who thought that Niklaus\n  Wirth actually knew what he was\n  talking about. He didn\'t. He doesn\'t\n  have a frigging clue."</p>\n</blockquote>\n\n<p>-</p>\n\n<blockquote>\n  <p>Linus: "I think goto\'s are fine, and\n  they are often more readable than\n  large amounts of indentation."</p>\n</blockquote>\n\n<p>-</p>\n\n<blockquote>\n  <p>Linus: "Of course, in stupid languages\n  like Pascal, where labels cannot be \n  descriptive, goto\'s can be bad."</p>\n</blockquote>\n'}, {'answer_id': 47467, 'author': 'Bruno Ranschaert', 'author_id': 4900, 'author_profile': 'https://Stackoverflow.com/users/4900', 'pm_score': 5, 'selected': False, 'text': '<p>Donald E. Knuth answered this question in the book "Literate Programming", 1992 CSLI. On p. 17 there is an essay "<a href="http://pplab.snu.ac.kr/courses/adv_pl05/papers/p261-knuth.pdf" rel="noreferrer">Structured Programming with goto Statements</a>" (PDF). I think the article might have been published in other books as well.</p>\n\n<p>The article describes Dijkstra\'s suggestion and describes the circumstances where this is valid. But he also gives a number of counter examples (problems and algorithms) which cannot be easily reproduced using structured loops only.</p>\n\n<p>The article contains a complete description of the problem, the history, examples and counter examples.</p>\n'}, {'answer_id': 47472, 'author': 'shsteimer', 'author_id': 292, 'author_profile': 'https://Stackoverflow.com/users/292', 'pm_score': 7, 'selected': False, 'text': '<p>I can only recall using a goto once.  I had a series of five nested counted loops and I needed to be able to break out of the entire structure from the inside early based on certain conditions:</p>\n<pre class="lang-c prettyprint-override"><code>    for{\n      for{\n        for{\n          for{\n            for{\n              if(stuff){\n                GOTO ENDOFLOOPS;\n              }\n            }\n          }\n        }\n      }\n    }\n    \n    ENDOFLOOPS:\n</code></pre>\n<p>I could just have easily declared a boolean break variable and used it as part of the conditional for each loop, but in this instance I decided a GOTO was just as practical and just as readable.</p>\n<p><strong>No velociraptors attacked me.</strong></p>\n'}, {'answer_id': 47476, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 7, 'selected': False, 'text': '<p>We already had this <a href="https://stackoverflow.com/questions/24451/goto-usage">discussion</a> and I stand by <a href="https://stackoverflow.com/questions/24451/goto-usage#24475">my point</a>.</p>\n\n<p>Furthermore, I\'m fed up with people describing higher-level language structures as “<code>goto</code> in disguise” because they clearly haven\'t got the point <em>at all</em>. For example:</p>\n\n<blockquote>\n  <p>Even the advanced continuation control structure in Scheme can be described as a sophisticated goto.</p>\n</blockquote>\n\n<p>That is complete nonsense. <em>Every</em> control structure can be implemented in terms of <code>goto</code> but this observation is utterly trivial and useless. <code>goto</code> isn\'t considered harmful because of its positive effects but because of its negative consequences and these have been eliminated by structured programming.</p>\n\n<p>Similarly, saying “GOTO is a tool, and as all tools, it can be used and abused” is completely off the mark. No modern construction worker would use a rock and claim it “is a tool.” Rocks have been replaced by hammers. <code>goto</code> has been replaced by control structures. If the construction worker were stranded in the wild without a hammer, of course he would use a rock instead. If a programmer has to use an inferior programming language that doesn\'t have feature X, well, of course she may have to use <code>goto</code> instead. But if she uses it anywhere else instead of the appropriate language feature she clearly hasn\'t understood the language properly and uses it wrongly. It\'s really as simple as that.</p>\n'}, {'answer_id': 47512, 'author': 'DrPizza', 'author_id': 2131, 'author_profile': 'https://Stackoverflow.com/users/2131', 'pm_score': 3, 'selected': False, 'text': '<p>Until C and C++ (amongst other culprits) have labelled breaks and continues, goto will continue to have a role.</p>\n'}, {'answer_id': 47517, 'author': 'smh', 'author_id': 1077, 'author_profile': 'https://Stackoverflow.com/users/1077', 'pm_score': 6, 'selected': False, 'text': '<p>In C, <code>goto</code> only works within the scope of the current function, which tends to localise any potential bugs. <code>setjmp</code> and <code>longjmp</code> are far more dangerous, being non-local, complicated and implementation-dependent. In practice however, they\'re too obscure and uncommon to cause many problems.</p>\n\n<p>I believe that the danger of <code>goto</code> in C is greatly exaggerated. Remember that the original <code>goto</code> arguments took place back in the days of languages like old-fashioned BASIC, where beginners would write spaghetti code like this:</p>\n\n<pre><code>3420 IF A &gt; 2 THEN GOTO 1430\n</code></pre>\n\n<p>Here Linus describes an appropriate use of <code>goto</code>: <a href="http://www.kernel.org/doc/Documentation/CodingStyle" rel="noreferrer">http://www.kernel.org/doc/Documentation/CodingStyle</a> (chapter 7).</p>\n'}, {'answer_id': 47590, 'author': 'vt.', 'author_id': 3905, 'author_profile': 'https://Stackoverflow.com/users/3905', 'pm_score': 4, 'selected': False, 'text': "<p>If you're writing a VM in C, it turns out that using (gcc's) computed gotos like this:</p>\n\n<pre><code>char run(char *pc) {\n    void *opcodes[3] = {&&op_inc, &&op_lda_direct, &&op_hlt};\n    #define NEXT_INSTR(stride) goto *(opcodes[*(pc += stride)])\n    NEXT_INSTR(0);\n    op_inc:\n    ++acc;\n    NEXT_INSTR(1);\n    op_lda_direct:\n    acc = ram[++pc];\n    NEXT_INSTR(1);\n    op_hlt:\n    return acc;\n}</code></pre>\n\n<p>works much faster than the conventional switch inside a loop.</p>\n"}, {'answer_id': 52307, 'author': 'joel.neely', 'author_id': 3525, 'author_profile': 'https://Stackoverflow.com/users/3525', 'pm_score': 9, 'selected': True, 'text': '<p>The following statements are generalizations; while it is always possible to plead exception, it usually (in my experience and humble opinion) isn\'t worth the risks.</p>\n<ol>\n<li>Unconstrained use of memory addresses (either GOTO or raw pointers) provides too many opportunities to make easily avoidable mistakes.</li>\n<li>The more ways there are to arrive at a particular &quot;location&quot; in the code, the less confident one can be about what the state of the system is at that point. (See below.)</li>\n<li>Structured programming IMHO is less about &quot;avoiding GOTOs&quot; and more about making the structure of the code match the structure of the data. For example, a repeating data structure (e.g. array, sequential file, etc.) is naturally processed by a repeated unit of code. Having built-in structures (e.g. while, for, until, for-each, etc.) allows the programmer to avoid the tedium of repeating the same cliched code patterns.</li>\n<li>Even if GOTO is low-level implementation detail (not always the case!) it\'s below the level that the programmer should be thinking. How many programmers balance their personal checkbooks in raw binary? How many programmers worry about which sector on the disk contains a particular record, instead of just providing a key to a database engine (and how many ways could things go wrong if we really wrote all of our programs in terms of physical disk sectors)?</li>\n</ol>\n<p>Footnotes to the above:</p>\n<p>Regarding point 2, consider the following code:</p>\n<pre class="lang-c prettyprint-override"><code>    a = b + 1\n    /* do something with a */\n</code></pre>\n<p>At the &quot;do something&quot; point in the code, we can state with high confidence that <code>a</code> is greater than <code>b</code>. (Yes, I\'m ignoring the possibility of untrapped integer overflow. Let\'s not bog down a simple example.)</p>\n<p>On the other hand, if the code had read this way:</p>\n<pre class="lang-c prettyprint-override"><code>    ...\n    goto 10\n    ...\n    a = b + 1\n    10: /* do something with a */\n    ...\n    goto 10\n    ...\n</code></pre>\n<p>The multiplicity of ways to get to label 10 means that we have to work much harder to be confident about the relationships between <code>a</code> and <code>b</code> at that point. (In fact, in the general case it\'s undecideable!)</p>\n<p>Regarding point 4, the whole notion of &quot;going someplace&quot; in the code is just a metaphor. Nothing is really &quot;going&quot; anywhere inside the CPU except electrons and photons (for the waste heat). Sometimes we give up a metaphor for another, more useful, one. I recall encountering (a few decades ago!) a language where</p>\n<pre class="lang-c prettyprint-override"><code>    if (some condition) {\n      action-1\n    } else {\n      action-2\n    }\n</code></pre>\n<p>was implemented on a virtual machine by compiling action-1 and action-2 as out-of-line parameterless routines, then using a single two-argument VM opcode which used the boolean value of the condition to invoke one or the other. The concept was simply &quot;choose what to invoke now&quot; rather than &quot;go here or go there&quot;. Again, just a change of metaphor.</p>\n'}, {'answer_id': 52345, 'author': 'srclontz', 'author_id': 4606, 'author_profile': 'https://Stackoverflow.com/users/4606', 'pm_score': 1, 'selected': False, 'text': '<p>Using a goto makes it far too easy to write "spaghetti code" which is not particularly maintainable.  The most important rule to follow is to write readable code, but of course it depends on what the goals of the project are.  As a "best practice" avoiding a goto is a good idea.  It\'s something extreme programming types would refer to as "code smell" because it indicates that you may be doing something wrong.  Using a break while looping is remarkably similar to a goto, except it isn\'t a goto, but again is an indication that the code may not be optimal.  This is why, I believe, it is also important to not find more modern programming loopholes which are essentially a goto by a different name. </p>\n'}, {'answer_id': 119103, 'author': 'Steve Jessop', 'author_id': 13005, 'author_profile': 'https://Stackoverflow.com/users/13005', 'pm_score': 7, 'selected': False, 'text': '<p>Goto is extremely low on my list of things to include in a program just for the sake of it. That doesn\'t mean it\'s unacceptable.</p>\n\n<p>Goto can be nice for state machines. A switch statement in a loop is (in order of typical importance): (a) not actually representative of the control flow, (b) ugly, (c) potentially inefficient depending on language and compiler. So you end up writing one function per state, and doing things like "return NEXT_STATE;" which even look like goto.</p>\n\n<p>Granted, it is difficult to code state machines in a way which make them easy to understand. However, none of that difficulty is to do with using goto, and none of it can be reduced by using alternative control structures. Unless your language has a \'state machine\' construct. Mine doesn\'t.</p>\n\n<p>On those rare occasions when your algorithm really is most comprehensible in terms of a path through a sequence of nodes (states) connected by a limited set of permissible transitions (gotos), rather than by any more specific control flow (loops, conditionals, whatnot), then that should be explicit in the code. And you ought to draw a pretty diagram.</p>\n\n<p>setjmp/longjmp can be nice for implementing exceptions or exception-like behaviour. While not universally praised, exceptions are generally considered a "valid" control structure.</p>\n\n<p>setjmp/longjmp are \'more dangerous\' than goto in the sense that they\'re harder to use correctly, never mind comprehensibly.</p>\n\n<blockquote>\n  <p>There never has been, nor will there\n  ever be, any language in which it is\n  the least bit difficult to write bad\n  code. -- Donald Knuth.</p>\n</blockquote>\n\n<p>Taking goto out of C would not make it any easier to write good code in C. In fact, it would rather miss the point that C is <em>supposed</em> to be capable of acting as a glorified assembler language.</p>\n\n<p>Next it\'ll be "pointers considered harmful", then "duck typing considered harmful". Then who will be left to defend you when they come to take away your unsafe programming construct? Eh?</p>\n'}, {'answer_id': 122836, 'author': 'eet_1024', 'author_id': 21302, 'author_profile': 'https://Stackoverflow.com/users/21302', 'pm_score': 2, 'selected': False, 'text': "<p>On every platform I have seen, high level control structures are implemented as low level gotos (jumps).  For example, the Java Virtual Machine has a Jump byte code, but nothing for if, else, while, for, etc.</p>\n\n<p>And some of these compilers create spaghetti code for a simple conditional block.</p>\n\n<p>To answer your question, goto is still considered harmful by people who believe it to be harmful.  Goto makes it easy to lose the advantages of structured programming.</p>\n\n<p>In the end, it's your program; and therefore your decision.  I suggest not using goto until you are able to answer your question yourself, but in the context of a specific problem.</p>\n"}, {'answer_id': 323815, 'author': 'Mike Dunlavey', 'author_id': 23771, 'author_profile': 'https://Stackoverflow.com/users/23771', 'pm_score': 3, 'selected': False, 'text': "<p>If GOTO itself were evil, compilers would be evil, because they generate JMPs. If jumping into a block of code, especially following a pointer, were inherently evil, the RETurn instruction would be evil. Rather, the evil is in the potential for abuse.</p>\n\n<p>At times I have had to write apps that had to keep track of a number of objects where each object had to follow an intricate sequence of states in response to events, but the whole thing was definitely single-thread. A typical sequence of states, if represented in pseudo-code would be:</p>\n\n<pre><code>request something\nwait for it to be done\nwhile some condition\n    request something\n    wait for it\n    if one response\n        while another condition\n            request something\n            wait for it\n            do something\n        endwhile\n        request one more thing\n        wait for it\n    else if some other response\n        ... some other similar sequence ...\n    ... etc, etc.\nendwhile\n</code></pre>\n\n<p>I'm sure this is not new, but the way I handled it in C(++) was to define some macros:</p>\n\n<pre><code>#define WAIT(n) do{state=(n); enque(this); return; L##n:;}while(0)\n#define DONE state = -1\n\n#define DISPATCH0 if state &lt; 0) return;\n#define DISPATCH1 if(state==1) goto L1; DISPATCH0\n#define DISPATCH2 if(state==2) goto L2; DISPATCH1\n#define DISPATCH3 if(state==3) goto L3; DISPATCH2\n#define DISPATCH4 if(state==4) goto L4; DISPATCH3\n... as needed ...\n</code></pre>\n\n<p>Then (assuming state is initially 0) the structured state machine above turns into the structured code:</p>\n\n<pre><code>{\n    DISPATCH4; // or as high a number as needed\n    request something;\n    WAIT(1); // each WAIT has a different number\n    while (some condition){\n        request something;\n        WAIT(2);\n        if (one response){\n            while (another condition){\n                request something;\n                WAIT(3);\n                do something;\n            }\n            request one more thing;\n            WAIT(4);\n        }\n        else if (some other response){\n            ... some other similar sequence ...\n        }\n        ... etc, etc.\n    }\n    DONE;\n}\n</code></pre>\n\n<p>With a variation on this, there can be CALL and RETURN, so some state machines can act like subroutines of other state machines.</p>\n\n<p>Is it unusual? Yes. Does it take some learning on the part of the maintainer? Yes. Does that learning pay off? I think so. Could it be done without GOTOs that jump into blocks? Nope.</p>\n"}, {'answer_id': 325005, 'author': 'J.T. Hurley', 'author_id': 39851, 'author_profile': 'https://Stackoverflow.com/users/39851', 'pm_score': 1, 'selected': False, 'text': "<p>Once, early in my programming life, I produced a program that consisted of a series of functions in a chain, where each function called its successor given successful conditions and completions.</p>\n\n<p>It was a hideous cludge that had multiple serious problems, the most serious being that no function could terminate until all the functions under it had terminated.</p>\n\n<p>But it was quickly developed, worked well for the limited set of problems it was designed to solve, and was showed the logic and flow of the program explicitly, which worked well when I refactored and extended it for inclusion in another project.</p>\n\n<p>My vote's on use it when it makes sense, and refactor it out as soon as its convenient.</p>\n"}, {'answer_id': 357028, 'author': 'CurtTampa', 'author_id': 18225, 'author_profile': 'https://Stackoverflow.com/users/18225', 'pm_score': 4, 'selected': False, 'text': "<p>Denying the use of the GOTO statement to programmers is like telling a carpenter not to use a hammer as it Might damage the wall while he is hammering in a nail. A real programmer Knows How and When to use a GOTO. I’ve followed behind some of these so-called ‘Structured Programs’ I’ve see such Horrid code just to avoid using a GOTO, that I could shoot the programmer. Ok, In defense of the other side, I’ve seen some real spaghetti code too and again, those programmers should be shot too.</p>\n\n<p>Here is just one small example of code I’ve found.</p>\n\n<pre><code>  YORN = ''\n  LOOP\n  UNTIL YORN = 'Y' OR YORN = 'N' DO\n     CRT 'Is this correct? (Y/N) : ':\n     INPUT YORN\n  REPEAT\n  IF YORN = 'N' THEN\n     CRT 'Aborted!'\n     STOP\n  END\n</code></pre>\n\n<p>-----------------------OR----------------------</p>\n\n<pre><code>10:  CRT 'Is this Correct (Y)es/(N)o ':\n\n     INPUT YORN\n\n     IF YORN='N' THEN\n        CRT 'Aborted!'\n        STOP\n     ENDIF\n     IF YORN&lt;&gt;'Y' THEN GOTO 10\n</code></pre>\n"}, {'answer_id': 453816, 'author': 'Rocketmagnet', 'author_id': 55934, 'author_profile': 'https://Stackoverflow.com/users/55934', 'pm_score': 3, 'selected': False, 'text': "<p>I actually found myself forced to use a goto, because I literally couldn't think of a better (faster) way to write this code:</p>\n\n<p>I had a complex object, and I needed to do some operation on it. If the object was in one state, then I could do a quick version of the operation, otherwise I had to do a slow version of the operation.  The thing was that in some cases, in the middle of the slow operation, it was possible to realise that this could have been done with the fast operation.</p>\n\n<pre><code>SomeObject someObject;    \n\nif (someObject.IsComplex())    // this test is trivial\n{\n    // begin slow calculations here\n    if (result of calculations)\n    {\n        // just discovered that I could use the fast calculation !\n        goto Fast_Calculations;\n    }\n    // do the rest of the slow calculations here\n    return;\n}\n\nif (someObject.IsmediumComplex())    // this test is slightly less trivial\n{\n    Fast_Calculations:\n    // Do fast calculations\n    return;\n}\n\n// object is simple, no calculations needed.\n</code></pre>\n\n<p>This was in a speed critical piece of realtime UI code, so I honestly think that a GOTO was justified here.</p>\n\n<p>Hugo</p>\n"}, {'answer_id': 548701, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>"In this link <a href="http://kerneltrap.org/node/553/2131" rel="noreferrer">http://kerneltrap.org/node/553/2131</a>"</p>\n\n<p>Ironically, eliminating the goto introduced a bug: the spinlock call was omitted.</p>\n'}, {'answer_id': 548769, 'author': 'Jonathan Leffler', 'author_id': 15168, 'author_profile': 'https://Stackoverflow.com/users/15168', 'pm_score': 5, 'selected': False, 'text': '<p>Attracted by Jay Ballou adding an answer, I\'ll add my £0.02.  If Bruno Ranschaert had not already done so, I\'d have mentioned Knuth\'s &quot;Structured Programming with GOTO Statements&quot; article.</p>\n<p>One thing that I\'ve not seen discussed is the sort of code that, while not exactly common, was taught in Fortran text books.  Things like the extended range of a DO loop and open-coded subroutines (remember, this would be Fortran II, or Fortran IV, or Fortran 66 - not Fortran 77 or 90).  There\'s at least a chance that the syntactic details are inexact, but the concepts should be accurate enough.  The snippets in each case are inside a single function.</p>\n<p>Note that the excellent but dated (and out of print) book \'<a href="https://rads.stackoverflow.com/amzn/click/com/0070342075" rel="noreferrer" rel="nofollow noreferrer">The Elements of Programming Style, 2nd Edn</a>\' by Kernighan &amp; Plauger includes some real-life examples of abuse of GOTO from programming text books of its era (late-70s).  The material below is not from that book, however.</p>\n<h3>Extended range for a DO loop</h3>\n<pre><code>       do 10 i = 1,30\n           ...blah...\n           ...blah...\n           if (k.gt.4) goto 37\n91         ...blah...\n           ...blah...\n10     continue\n       ...blah...\n       return\n37     ...some computation...\n       goto 91\n</code></pre>\n<p>One reason for such nonsense was the good old-fashioned punch-card.  You might notice that the labels (nicely out of sequence because that was canonical style!) are in column 1 (actually, they had to be in columns 1-5) and the code is in columns 7-72 (column 6 was the continuation marker column).  Columns 73-80 would be given a sequence number, and there were machines that would sort punch card decks into sequence number order.  If you had your program on sequenced cards and needed to add a few cards (lines) into the middle of a loop, you\'d have to repunch everything after those extra lines.  However, if you replaced one card with the GOTO stuff, you could avoid resequencing all the cards - you just tucked the new cards at the end of the routine with new sequence numbers.  Consider it to be the first attempt at \'green computing\' - a saving of punch cards (or, more specifically, a saving of retyping labour - and a saving of consequential rekeying errors).</p>\n<p>Oh, you might also note that I\'m cheating and not shouting - Fortran IV was written in all upper-case normally.</p>\n<h3>Open-coded subroutine</h3>\n<pre><code>       ...blah...\n       i = 1\n       goto 76\n123    ...blah...\n       ...blah...\n       i = 2\n       goto 76\n79     ...blah...\n       ...blah...\n       goto 54\n       ...blah...\n12     continue\n       return\n76     ...calculate something...\n       ...blah...\n       goto (123, 79) i\n54     ...more calculation...\n       goto 12\n</code></pre>\n<p>The GOTO between labels 76 and 54 is a version of computed goto.  If the variable i has the value 1, goto the first label in the list (123); if it has the value 2, goto the second, and so on.  The fragment from 76 to the computed goto is the open-coded subroutine.  It was a piece of code executed rather like a subroutine, but written out in the body of a function.  (Fortran also had statement functions - which were embedded functions that fitted on a single line.)</p>\n<p>There were worse constructs than the computed goto - you could assign labels to variables and then use an assigned goto.  Googling <a href="http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlf101a.doc/xlflr/gotoass.htm" rel="noreferrer">assigned goto</a> tells me it was deleted from Fortran 95.  Chalk one up for the structured programming revolution which could fairly be said to have started in public with Dijkstra\'s &quot;GOTO Considered Harmful&quot; letter or article.</p>\n<p>Without some knowledge of the sorts of things that were done in Fortran (and in other languages, most of which have rightly fallen by the wayside), it is hard for us newcomers to understand the scope of the problem which Dijkstra was dealing with.  Heck, I didn\'t start programming until ten years after that letter was published (but I did have the misfortune to program in Fortran IV for a while).</p>\n'}, {'answer_id': 549764, 'author': 'mweiss', 'author_id': 33254, 'author_profile': 'https://Stackoverflow.com/users/33254', 'pm_score': 2, 'selected': False, 'text': "<p>While I think it's best to avoid goto on almost any situation, there are exceptions.\nFor example, one place I've seen where goto statements are the elegant solution compared to others much more convoluted ways is implementing tail call elimintation for an interpreter.  </p>\n"}, {'answer_id': 741446, 'author': 'Nicolas Dorier', 'author_id': 19803, 'author_profile': 'https://Stackoverflow.com/users/19803', 'pm_score': 0, 'selected': False, 'text': '<p>Look <a href="https://www.securecoding.cert.org/confluence/display/seccode/MEM12-C.+Use+a+Goto-Chain+when+leaving+a+function+on+error+when+using+and+releasing+resources" rel="nofollow noreferrer">this</a>, it\'s a good usse of GoTo, but in a language with garbage collector I think the only reason to use GoTo is to obfuscate your code (obfuscators tools use GoTo to hide their code)</p>\n'}, {'answer_id': 741455, 'author': 'stesch', 'author_id': 41860, 'author_profile': 'https://Stackoverflow.com/users/41860', 'pm_score': 4, 'selected': False, 'text': '<p>It never was, as long as you were able to think for yourself.</p>\n'}, {'answer_id': 741517, 'author': 'tylerl', 'author_id': 86060, 'author_profile': 'https://Stackoverflow.com/users/86060', 'pm_score': 5, 'selected': False, 'text': '<p>Go To can provide a sort of stand-in for "real" exception handling in certain cases. Consider:</p>\n\n<pre><code>ptr = malloc(size);\nif (!ptr) goto label_fail;\nbytes_in = read(f_in,ptr,size);\nif (bytes_in=&lt;0) goto label_fail;\nbytes_out = write(f_out,ptr,bytes_in);\nif (bytes_out != bytes_in) goto label_fail;\n</code></pre>\n\n<p>Obviously this code was simplified to take up less space, so don\'t get too hung up on the details. But consider an alternative I\'ve seen all too many times in <strong>production</strong> code by coders going to absurd lengths to avoid using goto:</p>\n\n<pre><code>success=false;\ndo {\n    ptr = malloc(size);\n    if (!ptr) break;\n    bytes_in = read(f_in,ptr,size);\n    if (count=&lt;0) break;\n    bytes_out = write(f_out,ptr,bytes_in);\n    if (bytes_out != bytes_in) break;\n    success = true;\n} while (false);\n</code></pre>\n\n<p>Now functionally this code does the exact same thing. In fact, the code generated by the compiler is nearly identical. However, in the programmer\'s zeal to appease <em>Nogoto</em> (the dreaded god of academic rebuke), this programmer has completely broken the underlying idiom that the <code>while</code> loop represents, and did a real number on the readability of the code. <strong>This is not better.</strong></p>\n\n<p>So, the moral of the story is, if you find yourself resorting to something really stupid in order to avoid using goto, then don\'t.</p>\n'}, {'answer_id': 780172, 'author': 'nelix', 'author_id': 93863, 'author_profile': 'https://Stackoverflow.com/users/93863', 'pm_score': 0, 'selected': False, 'text': "<p>Computed gotos for dispatch, often is easyer to understand than a very large switch statement.</p>\n\n<p>For errors and co-threads I think setcontex or setjmp (where available) are 'better'.</p>\n"}, {'answer_id': 780212, 'author': 'las3rjock', 'author_id': 94732, 'author_profile': 'https://Stackoverflow.com/users/94732', 'pm_score': 2, 'selected': False, 'text': '<p>Yes, GOTO is still considered harmful.  By the time you find yourself in the rare situation where the use of a GOTO might be valid, you should be confident enough in your own programming skill not to need the validation of others.  Any GOTO-like functions that allow you to jump even farther away in scope than allowed by GOTO should be considered more dangerous than GOTO.</p>\n'}, {'answer_id': 780245, 'author': 'smcameron', 'author_id': 77514, 'author_profile': 'https://Stackoverflow.com/users/77514', 'pm_score': 4, 'selected': False, 'text': '<p>Since I began doing a few things in the linux kernel, gotos don\'t bother me so much as they once did.  At first I was sort of horrified to see they (kernel guys) added gotos into my code.  I\'ve since become accustomed to the use of gotos, in some limited contexts, and will now occasionally use them myself.  Typically, it\'s a goto that jumps to the end of a function to do some kind of cleanup and bail out, rather than duplicating that same cleanup and bailout in several places in the function.  And typically, it\'s not something large enough to hand off to another function -- e.g. freeing some locally (k)malloc\'ed variables is a typical case.</p>\n\n<p>I\'ve written code that used setjmp/longjmp only once.  It was in a MIDI drum sequencer program.  Playback happened in a separate process from all user interaction, and the playback process used shared memory with the UI process to get the limited info it needed to do the playback.  When the user wanted to stop playback, the playback process just did a longjmp "back to the beginning" to start over, rather than some complicated unwinding of wherever it happened to be executing when the user wanted it to stop.  It worked great, was simple, and I never had any problems or bugs related to it in that instance.</p>\n\n<p>setjmp/longjmp have their place -- but that place is one you\'ll not likely visit but once in a very long while.</p>\n\n<p>Edit:  I just looked at the code.  It was actually siglongjmp() that I used, not longjmp (not that it\'s a big deal, but I had forgotten that siglongjmp even existed.)</p>\n'}, {'answer_id': 880151, 'author': 'mfx', 'author_id': 8015, 'author_profile': 'https://Stackoverflow.com/users/8015', 'pm_score': 0, 'selected': False, 'text': '<p>Using a GOTO can be nice when you are generating C state machines. I would never use a GOTO in hand-written code - "modern" language constructs make it utterly unnecessary.</p>\n\n<p>The setjmp/longjmp construct can be useful in certain circumstances (when "true" exceptions are missing, or when you are implementing something like Chicken scheme), but it has no place in "ordinary" programming.  </p>\n'}, {'answer_id': 1616884, 'author': 'Loren Pechtel', 'author_id': 10659, 'author_profile': 'https://Stackoverflow.com/users/10659', 'pm_score': 0, 'selected': False, 'text': "<p>In a perfect world we would never need a GOTO.  However, we live in an imperfect world.  We don't have compilers with every control structure we can dream of.  On occasion I feel it's better to use a GOTO than kludge a control structure that doesn't really exist.</p>\n\n<p>The most common (not that it's common) is the loop and a half construct.  You always execute the first part, maybe you execute the rest of it and then go back and do the first part again.  Sure, you can implement it with a boolean flag inside a while loop but I don't like this answer because it's less clear in my opinion.  When you see something like:</p>\n\n<pre><code>loop:\n  GetSomeData;\n  if GotData then\n     Begin\n        ProcessTheData;\n        StoreTheResult;\n        Goto Loop;\n     End;\n</code></pre>\n\n<p>to me it's clearer than</p>\n\n<pre><code>Repeat\n  GetSomeData;\n  Flag := GotData;\n  if Flag then\n    Begin\n      ProcessTheData;\n      StoreTheResult;\n    End;\nUntil Not Flag;\n</code></pre>\n\n<p>and there are times where</p>\n\n<pre><code>Function GotTheData;\n\nBegin\n  GetSomeData;\n  Result := GotData;\nEnd;\n\nWhile GotTheData do\n  Begin\n    ProcessTheData;\n    StoreTheResult;\n  End;\n</code></pre>\n\n<p>isn't a workable answer, and I'm a firm believer that code should be clear.  If I have to make a comment explaining what the code is doing I consider whether I could make the code clearer and get rid of the comment.</p>\n"}, {'answer_id': 1616905, 'author': 'John K', 'author_id': 179972, 'author_profile': 'https://Stackoverflow.com/users/179972', 'pm_score': 1, 'selected': False, 'text': '<p>Many modern programming languages use their compiler to enforce restrictions on the usage of GOTO - this cuts down on the potential risks. For example, C# will not allow you to use GOTO to jump into the body of a loop from outside of it. <a href="http://msdn.microsoft.com/en-us/library/aa664758(VS.71).aspx" rel="nofollow noreferrer">Restrictions are mentioned in the documentation</a>.</p>\n\n<p>This is one example of how GOTO is sometimes safer than it used to be.</p>\n\n<p>In some cases the use of GOTO is the same as returning early from a function (i.e. to break out of a loop early). However good form can be argued.</p>\n'}, {'answer_id': 1857927, 'author': 'DigitalRoss', 'author_id': 140740, 'author_profile': 'https://Stackoverflow.com/users/140740', 'pm_score': 4, 'selected': False, 'text': '<h2>Because <code>goto</code> can be used for confusing metaprogramming</h2>\n\n<p><code>Goto</code> is both a <em>high-level</em> and a <em>low-level</em> control expression, and as a result it just doesn\'t have a appropriate design pattern suitable for most problems.</p>\n\n<p>It\'s <em>low-level</em> in the sense that a goto is a primitive operation that implements something higher like <code>while</code> or <code>foreach</code> or something.</p>\n\n<p>It\'s <em>high-level</em> in the sense that when used in certain ways it takes code that executes in a clear sequence, in an uninterrupted fashion, except for structured loops, and it changes it into pieces of logic that are, with enough <code>goto</code>s, a grab-bag of logic being dynamically reassembled.</p>\n\n<p>So, there is a <em>prosaic</em> and an <em>evil</em> side to <code>goto</code>.</p>\n\n<p>The <em>prosaic side</em> is that an upward pointing goto can implement a perfectly reasonable loop and a downward-pointing goto can do a perfectly reasonable <code>break</code> or <code>return</code>. Of course, an actual <code>while</code>, <code>break</code>, or <code>return</code> would be a lot more readable, as the poor human wouldn\'t have to simulate the effect of the <code>goto</code> in order to get the big picture. So, a bad idea in general.</p>\n\n<p>The <em>evil side</em> involves a routine not using goto for while, break, or return, but using it for what\'s called <em>spaghetti logic</em>. In this case the goto-happy developer is constructing pieces of code out of a maze of goto\'s, and the only way to understand it is to simulate it mentally as a whole, a terribly tiring task when there are many goto\'s. I mean, imagine the trouble of evaluating code where the <code>else</code> is not precisely an inverse of the <code>if</code>, where nested <code>if</code>s might allow in some things that were rejected by the outer <code>if</code>, etc, etc.</p>\n\n<p>Finally, to really cover the subject, we should note that essentially all early languages except Algol initially made only single statements subject to their versions of <code>if-then-else</code>. So, the only way to do a conditional block was to <code>goto</code> around it using an inverse conditional. Insane, I know, but I\'ve read some old specs. Remember that the first computers were programmed in binary machine code so I suppose any kind of an HLL was a lifesaver; I guess they weren\'t too picky about exactly what HLL features they got.</p>\n\n<p>Having said all that I used to stick one <code>goto</code> into every program I wrote <em>"just to annoy the purists"</em>.</p>\n'}, {'answer_id': 2394549, 'author': 'dan04', 'author_id': 287586, 'author_profile': 'https://Stackoverflow.com/users/287586', 'pm_score': 6, 'selected': False, 'text': '<p>Today, it\'s hard to see the big deal about the <code>GOTO</code> statement because the "structured programming" people mostly won the debate and today\'s languages have sufficient control flow structures to avoid <code>GOTO</code>.</p>\n\n<p>Count the number of <code>goto</code>s in a modern C program.  Now add the number of <code>break</code>, <code>continue</code>, and <code>return</code> statements.  Furthermore, add the number of times you use <code>if</code>, <code>else</code>, <code>while</code>, <code>switch</code> or <code>case</code>.  That\'s about how many <code>GOTO</code>s your program would have had if you were writing in FORTRAN or BASIC in 1968 when Dijkstra wrote his letter.</p>\n\n<p>Programming languages at the time were lacking in control flow.  For example, in the original Dartmouth BASIC:</p>\n\n<ul>\n<li><p><code>IF</code> statements had no <code>ELSE</code>.  If you wanted one, you had to write:</p>\n\n<pre><code>100 IF NOT condition THEN GOTO 200\n...stuff to do if condition is true...\n190 GOTO 300\n200 REM else\n...stuff to do if condition is false...\n300 REM end if\n</code></pre></li>\n<li><p>Even if your <code>IF</code> statement didn\'t need an <code>ELSE</code>, it was still limited to a single line, which usually consisted of a <code>GOTO</code>.</p></li>\n<li><p>There was no <code>DO...LOOP</code> statement.  For non-<code>FOR</code> loops, you had to end the loop with an explicit <code>GOTO</code> or <code>IF...GOTO</code> back to the beginning.</p></li>\n<li><p>There was no <code>SELECT CASE</code>.  You had to use <code>ON...GOTO</code>.</p></li>\n</ul>\n\n<p>So, you ended up with a <em>lot</em> of <code>GOTO</code>s in your program.  And you couldn\'t depend on the restriction of <code>GOTO</code>s to within a single subroutine (because <code>GOSUB...RETURN</code> was such a weak concept of subroutines), so these <code>GOTO</code>s could go <em>anywhere</em>.  Obviously, this made control flow hard to follow.</p>\n\n<p>This is where the anti-<code>GOTO</code> movement came from.</p>\n'}, {'answer_id': 2394566, 'author': 'kyoryu', 'author_id': 129175, 'author_profile': 'https://Stackoverflow.com/users/129175', 'pm_score': 1, 'selected': False, 'text': "<p>In my opinion, 'goto being harmful' is more about encapsulation and consistency of state than anything else.</p>\n\n<p>Much code, even 'oo' code, has as bad messy state encapsultation as any spaghetti code ever did.</p>\n\n<p>The problem with 'goto considered harmful' is that it leaves the programmer who only looks at the mechanistic rule without the understanding the impression that the only flow control that should be available is the return method, and that very easily leads to passing much state around by reference - and <em>that</em> leads right back to a lack of state encapsulation, the very thing that 'goto considered harmful' was trying to get rid of.</p>\n\n<p>Follow the flow of control in a typical 'OO' codebase, and tell me that we don't still have spaghetti code....  (btw, I don't mean the 'ravioli' code that usuall gets so much hate - the path of execution of ravioli code is usually pretty straightforward, even if the object relationships aren't immediately obvious).</p>\n\n<p>Or, to put it a different way, avoiding gotos in favor of everything being a subroutine is only useful if each subroutine only modifies local state, that cannot be modified except via that subroutine (or at least that object).</p>\n"}, {'answer_id': 3059735, 'author': 'Adam Houldsworth', 'author_id': 358221, 'author_profile': 'https://Stackoverflow.com/users/358221', 'pm_score': 2, 'selected': False, 'text': "<p>Almost all situations where a goto can be used, you can do the same using other constructs.  Goto is used by the compiler anyway.</p>\n\n<p>I personally never use it explicitly, don't ever need to.</p>\n"}, {'answer_id': 3444091, 'author': 'Sled', 'author_id': 254477, 'author_profile': 'https://Stackoverflow.com/users/254477', 'pm_score': 1, 'selected': False, 'text': "<p>There are a few issues with goto. One is that it is difficult to see how the code flows. It is easier to see an if-block because of the curly braces, but a goto hides that from you. Also, while and if are also essentially gotos, but they help explain why you are jumping back and forth in your code. With a regular goto that you have to piece together yourself. </p>\n\n<p>As an excercise try writing some code for calculating the fibonacci sequence and see how hard it is to read when you are done.</p>\n\n<p>If you are going to be working on that code then I would recommend writing some unittests and rewriting it. Otherwise, just let it be.</p>\n\n<p>All that said, sometimes, for performance reasons, it 'may' be appropriate to use a goto.</p>\n"}, {'answer_id': 3444224, 'author': 'David Given', 'author_id': 404568, 'author_profile': 'https://Stackoverflow.com/users/404568', 'pm_score': 1, 'selected': False, 'text': "<p>It's not that goto in of itself is bad; it's that using goto when the same logic can be more clearly expressed in another way is bad. It can make the code very hard to follow and makes maintenance hard. Just go and look at some programs in Basic from the Bad Old Days as an example.</p>\n\n<p>In my opinion, in a modern language like C# we should never have a need for goto in normal circumstances. If I find myself using it, it's usually a sign that I need to rethink my logic --- there's almost certainly a clearer way of expressing the same code using normal code flow statements.</p>\n\n<p>That said, there <em>are</em> special purposes for which goto can be extremely useful (and I find myself getting annoyed at languages that don't have it). I mostly use it in C for breaking out of multiple levels of loops, or for error handling; I believe that C# has language features that mean you don't have to do this. (It's also really useful when producing autogenerated code, but that's not something most people encounter in real life.)</p>\n\n<p>There's also another problem with goto, which is purely political: a lot of people hate it, and using it in code, <em>even if justified</em>, may cause issues. If this is assignment code, then yes, rewrite it, or you're likely to get marked down. Otherwise I'd be inclined to leave it in until the next time you need to do maintenance on that section.</p>\n"}, {'answer_id': 10859707, 'author': 'Tim', 'author_id': 1110442, 'author_profile': 'https://Stackoverflow.com/users/1110442', 'pm_score': 2, 'selected': False, 'text': '<p>C++ contains constructors and destructors. This allows for a pattern know as RAII (resource allocation is initialization). Basically, you create a local stack variable, and the act of creating the stack variable opens a file, allocates memory, locks a mutex, or otherwise acquires a resource that must later be released.</p>\n\n<p>When the variable goes out of scope, the destructor runs and frees the resource.</p>\n\n<p>C doesn\'t have this feature. But you still often need to acquire resources at the beginning of a function, and release them at the end.</p>\n\n<p>Your function probably has one or more error conditions that cause it to return early. You don\'t want to duplicate the resource release code. The solution is to use goto.</p>\n\n<p>Example:</p>\n\n<pre><code>int\nfoo(const char *arg)\n{\n    char *argcopy = strdup(arg);\n\n    if (!isvalid(argcopy))\n        goto out1;\n\n    FILE *myfile = fopen(argcopy, "r");\n    if (myfile == NULL)\n      goto out1;\n\n    char bytes[10];\n    if (fread(bytes, sizeof(bytes), 1, myfile) != sizeof(mybytes))\n        goto out2;\n\n    /* do some actual work */\n    /* .... */\n    /* end of actual work */\n\n    out2:\n    fclose(myfile);\n\n    out1:\n    free(argcopy);\n\n    return 0;\n }\n</code></pre>\n'}, {'answer_id': 10921640, 'author': 'gkimsey', 'author_id': 1224427, 'author_profile': 'https://Stackoverflow.com/users/1224427', 'pm_score': 3, 'selected': False, 'text': '<p>One thing I\'ve not seen from <em>any</em> of the answers here is that a \'goto\' solution is often <strong>more efficient</strong> than one of the structured programming solutions often mentioned.</p>\n\n<p>Consider the many-nested-loops case, where using \'goto\' instead of a bunch of <code>if(breakVariable)</code> sections is obviously more efficient.  The solution "Put your loops in a function and use return" is often totally unreasonable.  In the likely case that the loops are using local variables, you now have to pass them all through function parameters, potentially handling loads of extra headaches that arise from that.</p>\n\n<p>Now consider the cleanup case, which I\'ve used myself quite often, and is so common as to have presumably been responsible for the try{} catch {} structure not available in many languages.  The number of checks and extra variables that are required to accomplish the same thing are far worse than the one or two instructions to make the jump, and again, the additional function solution is not a solution at all.  You can\'t tell me that\'s more manageable or more readable.</p>\n\n<p>Now code space, stack usage, and execution time may not matter enough in many situations to many programmers, but when you\'re in an embedded environment with only 2KB of code space to work with, 50 bytes of extra instructions to avoid one clearly defined \'goto\' is just laughable, and this is not as rare a situation as many high-level programmers believe.</p>\n\n<p>The statement that \'goto is harmful\' was very helpful in moving towards structured programming, even if it was always an over-generalization.  At this point, we\'ve all heard it enough to be wary of using it (as we should).  When it\'s obviously the right tool for the job, we don\'t need to be scared of it.</p>\n'}, {'answer_id': 14960832, 'author': 'guido', 'author_id': 389099, 'author_profile': 'https://Stackoverflow.com/users/389099', 'pm_score': 0, 'selected': False, 'text': '<p>Example of jump in Java <a href="http://www.docjar.com/html/api/java/lang/String.java.html" rel="nofollow">String class</a> source code:</p>\n\n<pre><code>int firstUpper;\n\n/* Now check if there are any characters that need to be changed. */\nscan: {\n    for (firstUpper = 0 ; firstUpper &lt; count; ) {\n         char c = value[offset+firstUpper];\n         if ((c &gt;= Character.MIN_HIGH_SURROGATE) &amp;&amp;\n                 (c &lt;= Character.MAX_HIGH_SURROGATE)) {\n             int supplChar = codePointAt(firstUpper);\n             if (supplChar != Character.toLowerCase(supplChar)) {\n                  break scan;\n             }\n             firstUpper += Character.charCount(supplChar);\n         } else {\n             if (c != Character.toLowerCase(c)) {\n                  break scan;\n             }\n             firstUpper++;\n         }\n     }\n     return this;\n}\n[... subsequent use of firstUpper ...]\n</code></pre>\n\n<p>this could be rewritten with very little overhead for instance as:</p>\n\n<pre><code> int firstUpper = indexOfFirstUpper();\n if (firstUpper &lt; 0) return this; \n</code></pre>\n\n<p>Even in modern languages, and even if I don\'t actually like the use of gotos but I consider those acceptable in many cases, in a low-level case like this one looks better to me (and it does a little more than just exiting the loop).</p>\n\n<p>No intention to reanimate a religion war.</p>\n'}, {'answer_id': 24473250, 'author': 'Akavall', 'author_id': 1078084, 'author_profile': 'https://Stackoverflow.com/users/1078084', 'pm_score': 1, 'selected': False, 'text': '<p><code>goto</code> can be useful, here is an <a href="https://github.com/mcostalba/Stockfish/blob/master/src/search.cpp" rel="nofollow">example</a> of very strong open-source chess engine stockfish written in <code>c++</code>. The <code>goto</code> just skips some conditions checking (efficiency gain) that the program would have to do if not for the <code>goto</code> statement. If the <code>goto</code> statement label is after the <code>goto</code> declaration, then they are pretty harmless and readable. </p>\n'}, {'answer_id': 25773503, 'author': 'thb', 'author_id': 1275653, 'author_profile': 'https://Stackoverflow.com/users/1275653', 'pm_score': 5, 'selected': False, 'text': '<p>Goto considered helpful.</p>\n\n<p>I started programming in 1975.  To 1970s-era programmers, the words "goto considered harmful" said more or less that new programming languages with modern control structures were worth trying.  We did try the new languages.  We quickly converted.  We never went back.</p>\n\n<p>We never went back, but, if you are younger, then you have never been there in the first place.</p>\n\n<p>Now, a background in ancient programming languages may not be very useful except as an indicator of the programmer\'s age.  Notwithstanding, younger programmers lack this background, so they no longer understand the message the slogan "goto considered harmful" conveyed <em>to its intended audience at the time it was introduced.</em></p>\n\n<p>Slogans one does not understand are not very illuminating.  It is probably best to forget such slogans.  Such slogans do not help.</p>\n\n<p>This particular slogan however, "Goto considered harmful," has taken on an undead life of its own.</p>\n\n<p>Can goto not be abused?  Answer: sure, but so what?  Practically every programming element <em>can</em> be abused.  The humble <code>bool</code> for example is abused more often than some of us would like to believe.</p>\n\n<p>By contrast, I cannot remember meeting a single, actual instance of goto abuse since 1990.</p>\n\n<p>The biggest problem with goto is probably not technical but social.  Programmers who do not know very much sometimes seem to feel that deprecating goto makes them sound smart.  You might have to satisfy such programmers from time to time.  Such is life.</p>\n\n<p>The worst thing about goto today is that it is not used enough.</p>\n'}]
['https://Stackoverflow.com/questions/46586', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/658/']