<p>I've long been under the impression that <code>goto</code> should never be used if possible.</p>
<p>However, while perusing libavcodec (which is written in C) the other day, I was surprised to notice multiple uses of it.</p>
<p>Is it ever advantageous to use <code>goto</code> in a language that supports loops and functions?  If so, why?   Please provide a concrete example that clearly justifies the use of a <code>goto</code>.</p>

[{'answer_id': 24455, 'author': 'Abhinav', 'author_id': 2617, 'author_profile': 'https://Stackoverflow.com/users/2617', 'pm_score': 1, 'selected': False, 'text': '<p>In Perl, use of a label to "goto" from a loop - using a "last" statement, which is similar to break.</p>\n\n<p>This allows better control over nested loops.</p>\n\n<p>The traditional goto <em>label</em> is supported too, but I\'m not sure there are too many instances where this is the only way to achieve what you want - subroutines and loops should suffice for most cases.</p>\n'}, {'answer_id': 24465, 'author': 'cschol', 'author_id': 2386, 'author_profile': 'https://Stackoverflow.com/users/2386', 'pm_score': -1, 'selected': False, 'text': "<p>The problem with 'goto' and the most important argument of the 'goto-less programming' movement is, that if you use it too frequently your code, although it might behave correctly, becomes unreadable, unmaintainable, unreviewable etc. In 99.99% of the cases 'goto' leads to spaghetti code. Personally, I cannot think of any good reason as to why I would use 'goto'.</p>\n"}, {'answer_id': 24466, 'author': 'Ari Pernick', 'author_id': 2564, 'author_profile': 'https://Stackoverflow.com/users/2564', 'pm_score': 3, 'selected': False, 'text': '<p>The rule with goto that we use is that goto is okay to for jumping forward to a single exit cleanup point in a function. In really complex functions we relax that rule to allow other jump forwards. In both cases we are avoiding deeply nested if statements that often occur with error code checking, which helps readability and maintance.</p>\n'}, {'answer_id': 24475, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 5, 'selected': False, 'text': "<p>Since <code>goto</code> makes reasoning about program flow hard<sup>1</sup> (aka. “spaghetti code”), <code>goto</code> is generally only used to compensate for missing features: The use of <code>goto</code> may actually be acceptable, but only if the language doesn't offer a more structured variant to obtain the same goal. Take Doubt's example:</p>\n\n<blockquote>\n  <p>The rule with goto that we use is that goto is okay to for jumping forward to a single exit cleanup point in a function.</p>\n</blockquote>\n\n<p>This is true – but only if the language doesn't allow structured exception handling with cleanup code (such as RAII or <code>finally</code>), which does the same job better (as it is specially built for doing it), or when there's a good reason not to employ structured exception handling (but you will never have this case except at a very low level).</p>\n\n<p>In most other languages, the only acceptable use of <code>goto</code> is to exit nested loops. And even there it is almost always better to lift the outer loop into an own method and use <code>return</code> instead.</p>\n\n<p>Other than that, <code>goto</code> is a sign that not enough thought has gone into the particular piece of code.</p>\n\n<hr>\n\n<p><sup>1</sup> Modern languages which support <code>goto</code> implement some restrictions (e.g. <code>goto</code> may not jump into or out of functions) but the problem fundamentally remains the same.</p>\n\n<p>Incidentally, the same is of course also true for other language features, most notably exceptions. And there are usually strict rules in place to only use these features where indicated, such as the rule not to use exceptions to control non-exceptional program flow.</p>\n"}, {'answer_id': 24476, 'author': 'Chris Gillum', 'author_id': 2069, 'author_profile': 'https://Stackoverflow.com/users/2069', 'pm_score': 9, 'selected': True, 'text': '<p>There are a few reasons for using the "goto" statement that I\'m aware of (some have spoken to this already):</p>\n\n<p><strong>Cleanly exiting a function</strong></p>\n\n<p>Often in a function, you may allocate resources and need to exit in multiple places.  Programmers can simplify their code by putting the resource cleanup code at the end of the function, and all "exit points" of the function would goto the cleanup label.  This way, you don\'t have to write cleanup code at every "exit point" of the function.</p>\n\n<p><strong>Exiting nested loops</strong></p>\n\n<p>If you\'re in a nested loop and need to break out of <em>all</em> loops, a goto can make this much cleaner and simpler than break statements and if-checks.</p>\n\n<p><strong>Low-level performance improvements</strong></p>\n\n<p>This is only valid in perf-critical code, but goto statements execute very quickly and can give you a boost when moving through a function.  This is a double-edged sword, however, because a compiler typically cannot optimize code that contains gotos.</p>\n\n<p>Note that in all these examples, gotos are restricted to the scope of a single function.</p>\n'}, {'answer_id': 24511, 'author': 'Jakub Šturc', 'author_id': 2361, 'author_profile': 'https://Stackoverflow.com/users/2361', 'pm_score': 5, 'selected': False, 'text': '<p>In <strong>C#</strong> <a href="http://msdn.microsoft.com/en-us/library/06tc147t.aspx" rel="nofollow noreferrer">switch</a> statement <a href="http://msdn.microsoft.com/en-us/vcsharp/aa336815.aspx" rel="nofollow noreferrer">doest not allow fall-through</a>. So <a href="http://msdn.microsoft.com/en-us/library/13940fs2.aspx" rel="nofollow noreferrer">goto</a> is used to transfer control to a specific switch-case label or the <a href="http://msdn.microsoft.com/en-us/library/25tdedf5.aspx" rel="nofollow noreferrer">default</a> label.</p>\n<p>For example:</p>\n<pre><code>switch(value)\n{\n  case 0:\n    Console.WriteLine(&quot;In case 0&quot;);\n    goto case 1;\n  case 1:\n    Console.WriteLine(&quot;In case 1&quot;);\n    goto case 2;\n  case 2:\n    Console.WriteLine(&quot;In case 2&quot;);\n    goto default;\n  default:\n    Console.WriteLine(&quot;In default&quot;);\n    break;\n}\n</code></pre>\n<p><em>Edit: There is one exception on &quot;no fall-through&quot; rule. Fall-through is allowed if a case statement has no code.</em></p>\n'}, {'answer_id': 24513, 'author': 'DrPizza', 'author_id': 2131, 'author_profile': 'https://Stackoverflow.com/users/2131', 'pm_score': 2, 'selected': False, 'text': "<blockquote>\n  <p>If so, why?</p>\n</blockquote>\n\n<p>C has no multi-level/labelled break, and not all control flows can be easily modelled with C's iteration and decision primitives.  gotos go a long way towards redressing these flaws.</p>\n\n<p>Sometimes it's clearer to use a flag variable of some kind to effect a kind of pseudo-multi-level break, but it's not always superior to the goto (at least a goto allows one to easily determine where control goes to, unlike a flag variable), and sometimes you simply don't want to pay the performance price of flags/other contortions to avoid the goto.</p>\n\n<p>libavcodec is a performance-sensitive piece of code. Direct expression of the control flow is probably a priority, because it'll tend to run better.</p>\n"}, {'answer_id': 24537, 'author': 'Anders Eurenius', 'author_id': 1421, 'author_profile': 'https://Stackoverflow.com/users/1421', 'pm_score': 3, 'selected': False, 'text': '<p>One of the reasons goto is bad, besides coding style is that you can use it to create <em>overlapping</em>, but <em>non-nested</em> loops:</p>\n\n<pre><code>loop1:\n  a\nloop2:\n  b\n  if(cond1) goto loop1\n  c\n  if(cond2) goto loop2\n</code></pre>\n\n<p>This would create the bizarre, but possibly legal flow-of-control structure where a sequence like (a, b, c, b, a, b, a, b, ...) is possible, which makes compiler hackers unhappy. Apparently there are a number of clever optimization tricks that rely on this type of structure not occuring. (I should check my copy of the dragon book...) The result of this might (using some compilers) be that other optimizations aren\'t done for code that contains <code>goto</code>s.</p>\n\n<p>It might be useful if you <em>know</em> it just, "oh, by the way", happens to persuade the compiler to emit faster code. Personally, I\'d prefer to try to explain to the compiler about what\'s probable and what\'s not before using a trick like goto, but arguably, I might also try <code>goto</code> before hacking assembler.</p>\n'}, {'answer_id': 25598, 'author': 'C. K. Young', 'author_id': 13, 'author_profile': 'https://Stackoverflow.com/users/13', 'pm_score': 4, 'selected': False, 'text': '<p><code>#ifdef TONGUE_IN_CHEEK</code></p>\n\n<p>Perl has a <code>goto</code> that allows you to implement poor-man\'s tail calls. :-P</p>\n\n<pre><code>sub factorial {\n    my ($n, $acc) = (@_, 1);\n    return $acc if $n &lt; 1;\n    @_ = ($n - 1, $acc * $n);\n    goto &amp;factorial;\n}\n</code></pre>\n\n<p><code>#endif</code></p>\n\n<p>Okay, so that has nothing to do with C\'s <code>goto</code>. More seriously, I agree with the other comments about using <code>goto</code> for cleanups, or for implementing <a href="http://en.wikipedia.org/wiki/Duff&#39;s_device" rel="noreferrer">Duff\'s device</a>, or the like. It\'s all about using, not abusing.</p>\n\n<p>(The same comment can apply to <code>longjmp</code>, exceptions, <a href="http://en.wikipedia.org/wiki/call-with-current-continuation" rel="noreferrer"><code>call/cc</code></a>, and the like---they have legitimate uses, but can easily be abused. For example, throwing an exception purely to escape a deeply-nested control structure, under completely non-exceptional circumstances.)</p>\n'}, {'answer_id': 25630, 'author': 'bubbassauro', 'author_id': 1328, 'author_profile': 'https://Stackoverflow.com/users/1328', 'pm_score': -1, 'selected': False, 'text': '<p>Edsger Dijkstra, a computer scientist that had major contributions on the field, was also famous for criticizing the use of GoTo.\nThere\'s a short article about his argument on <a href="http://en.wikipedia.org/wiki/Goto" rel="nofollow noreferrer">Wikipedia</a>.</p>\n'}, {'answer_id': 74375, 'author': 'Brad Gilbert', 'author_id': 1337, 'author_profile': 'https://Stackoverflow.com/users/1337', 'pm_score': 2, 'selected': False, 'text': '<p>In a Perl module, you occasionally want to create subroutines or closures on the fly. The thing is, that once you have created the subroutine, how do you get to it. You could just call it, but then if the subroutine uses <a href="http://perldoc.perl.org/functions/caller.html" rel="nofollow noreferrer" title="perldoc -f caller"><code>caller()</code></a> it won\'t be as helpful as it could be. That is where the <a href="http://perldoc.perl.org/functions/goto.html" rel="nofollow noreferrer" title="perldoc -f goto"><code>goto &amp;subroutine</code></a> variation can be helpful.</p>\n\n<h3>Here is a quick example:</h3>\n<pre class="lang-perl prettyprint-override"><code>sub AUTOLOAD{\n  my($self) = @_;\n  my $name = $AUTOLOAD;\n  $name =~ s/.*:://;\n\n  *{$name} = my($sub) = sub{\n    # the body of the closure\n  }\n\n  goto $sub;\n\n  # nothing after the goto will ever be executed.\n}\n</code></pre>\n<hr />\n<p>You can also use this form of <code>goto</code> to provide a rudimentary form of tail-call optimization.</p>\n<pre class="lang-perl prettyprint-override"><code>sub factorial($){\n  my($n,$tally) = (@_,1);\n\n  return $tally if $n &lt;= 1;\n\n  $tally *= $n--;\n  @_ = ($n,$tally);\n  goto &amp;factorial;\n}\n</code></pre>\n<p>( In <a href="http://perldoc.perl.org/perl5160delta.html#__SUB__" rel="nofollow noreferrer">Perl 5 version 16</a> that would be better written as <a href="http://perldoc.perl.org/functions/__SUB__.html" rel="nofollow noreferrer"><code>goto __SUB__;</code></a> )</p>\n<p>There is a module that will import a <a href="https://metacpan.org/pod/Sub::Call::Tail" rel="nofollow noreferrer" title="Sub::Call::Tail"><code>tail</code></a> modifier and one that will import <a href="https://metacpan.org/pod/Sub::Call::Recur" rel="nofollow noreferrer" title="Sub::Call::Recur"><code>recur</code></a> if you don\'t like using this form of <a href="http://perldoc.perl.org/functions/goto.html" rel="nofollow noreferrer" title="perldoc -f goto"><code>goto</code></a>.</p>\n<pre class="lang-perl prettyprint-override"><code>use Sub::Call::Tail;\nsub AUTOLOAD {\n  ...\n  tail &amp;$sub( @_ );\n}\n\nuse Sub::Call::Recur;\nsub factorial($){\n  my($n,$tally) = (@_,1);\n\n  return $tally if $n &lt;= 1;\n  recur( $n-1, $tally * $n );\n}\n</code></pre>\n<hr />\n<h3>Most of the other reasons to use <code>goto</code> are better done with other keywords.</h3>\n<p>Like <a href="http://perldoc.perl.org/functions/redo.html" rel="nofollow noreferrer" title="perldoc -f redo"><code>redo</code></a>ing a bit of code:</p>\n<pre class="lang-perl prettyprint-override"><code>LABEL: ;\n...\ngoto LABEL if $x;\n</code></pre>\n\n<pre class="lang-perl prettyprint-override"><code>{\n  ...\n  redo if $x;\n}\n</code></pre>\n<p>Or going to the <a href="http://perldoc.perl.org/functions/last.html" rel="nofollow noreferrer" title="perldoc -f last"><code>last</code></a> of a bit of code from multiple places:</p>\n<pre class="lang-perl prettyprint-override"><code>goto LABEL if $x;\n...\ngoto LABEL if $y;\n...\nLABEL: ;\n</code></pre>\n\n<pre class="lang-perl prettyprint-override"><code>{\n  last if $x;\n  ...\n  last if $y\n  ...\n}\n</code></pre>\n'}, {'answer_id': 74791, 'author': 'bugmagnet', 'author_id': 426, 'author_profile': 'https://Stackoverflow.com/users/426', 'pm_score': 4, 'selected': False, 'text': '<p>I\'ve written more than a few lines of assembly language over the years. Ultimately, every high level language compiles down to gotos. Okay, call them "branches" or "jumps" or whatever else, but they\'re gotos. Can anyone write goto-less assembler? </p>\n\n<p>Now sure, you can point out to a Fortran, C or BASIC programmer that to run riot with gotos is a recipe for spaghetti bolognaise. The answer however is not to avoid them, but to use them carefully. </p>\n\n<p>A knife can be used to prepare food, free someone, or kill someone. Do we do without knives through fear of the latter? Similarly the goto: used carelessly it hinders, used carefully it helps.</p>\n'}, {'answer_id': 2187203, 'author': 'dsimcha', 'author_id': 23903, 'author_profile': 'https://Stackoverflow.com/users/23903', 'pm_score': 7, 'selected': False, 'text': "<p>Obeying best practices blindly is not a best practice.  The idea of avoiding <code>goto</code> statements as one's primary form of flow control is to avoid producing unreadable spaghetti code.  If used sparingly in the right places, they can sometimes be the simplest, clearest way of expressing an idea.  Walter Bright, the creator of the Zortech C++ compiler and the D programming language, uses them frequently, but judiciously.  Even with the <code>goto</code> statements, his code is still perfectly readable.  </p>\n\n<p>Bottom line:  Avoiding <code>goto</code> for the sake of avoiding <code>goto</code> is pointless.  What you really want to avoid is producing unreadable code.  If your <code>goto</code>-laden code is readable, then there's nothing wrong with it.</p>\n"}, {'answer_id': 2809244, 'author': 'Ricardo', 'author_id': 338062, 'author_profile': 'https://Stackoverflow.com/users/338062', 'pm_score': 3, 'selected': False, 'text': "<p>I find it funny that some people will go as far as to give a list of cases where goto is acceptable, saying that all other uses are unacceptable. Do you really think that you know every case where goto is the best choice for expressing an algorithm?</p>\n\n<p>To illustrate, I'll give you an example that no one here has shown yet:</p>\n\n<p>Today I was writing code for inserting an element in a hash table. The hash table is a cache of previous calculations which can be overwritten at will (affecting performance but not correctness).</p>\n\n<p>Each bucket of the hash table has 4 slots, and I have a bunch of criteria to decide which element to overwrite when a bucket is full. Right now this means making up to three passes through a bucket, like this:</p>\n\n<pre><code>// Overwrite an element with same hash key if it exists\nfor (add_index=0; add_index &lt; ELEMENTS_PER_BUCKET; add_index++)\n  if (slot_p[add_index].hash_key == hash_key)\n    goto add;\n\n// Otherwise, find first empty element\nfor (add_index=0; add_index &lt; ELEMENTS_PER_BUCKET; add_index++)\n  if ((slot_p[add_index].type == TT_ELEMENT_EMPTY)\n    goto add;\n\n// Additional passes go here...\n\nadd:\n// element is written to the hash table here\n</code></pre>\n\n<p>Now if I didn't use goto, what would this code look like?</p>\n\n<p>Something like this:</p>\n\n<pre><code>// Overwrite an element with same hash key if it exists\nfor (add_index=0; add_index &lt; ELEMENTS_PER_BUCKET; add_index++)\n  if (slot_p[add_index].hash_key == hash_key)\n    break;\n\nif (add_index &gt;= ELEMENTS_PER_BUCKET) {\n  // Otherwise, find first empty element\n  for (add_index=0; add_index &lt; ELEMENTS_PER_BUCKET; add_index++)\n    if ((slot_p[add_index].type == TT_ELEMENT_EMPTY)\n      break;\n  if (add_index &gt;= ELEMENTS_PER_BUCKET)\n   // Additional passes go here (nested further)...\n}\n\n// element is written to the hash table here\n</code></pre>\n\n<p>It would look worse and worse if more passes are added, while the version with goto keeps the same indentation level at all times and avoids the use of spurious if statements whose result is implied by the execution of the previous loop.</p>\n\n<p>So there's another case where goto makes the code cleaner and easier to write and understand... I'm sure there are many more, so don't pretend to know all the cases where goto is useful, dissing any good ones that you couldn't think of.</p>\n"}, {'answer_id': 2809313, 'author': 'Viktor Sehr', 'author_id': 100724, 'author_profile': 'https://Stackoverflow.com/users/100724', 'pm_score': 5, 'selected': False, 'text': "<p>Well, there's one thing that's always worse than <code>goto's</code>; strange use of other programflow operators to avoid a goto:</p>\n\n<p><strong>Examples:</strong></p>\n\n<pre><code>    // 1\n    try{\n      ...\n      throw NoErrorException;\n      ...\n    } catch (const NoErrorException&amp; noe){\n      // This is the worst\n    } \n\n\n    // 2\n    do {\n      ...break; \n      ...break;\n    } while (false);\n\n\n    // 3\n    for(int i = 0;...) { \n      bool restartOuter = false;\n      for (int j = 0;...) {\n        if (...)\n          restartOuter = true;\n      if (restartOuter) {\n        i = -1;\n      }\n    }\n\netc\netc\n</code></pre>\n"}, {'answer_id': 2809622, 'author': 'JUST MY correct OPINION', 'author_id': 282658, 'author_profile': 'https://Stackoverflow.com/users/282658', 'pm_score': 10, 'selected': False, 'text': '<p>Everybody who is anti-<code>goto</code> cites, directly or indirectly, Edsger Dijkstra\'s <a href="http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html" rel="noreferrer">GoTo Considered Harmful</a> article to substantiate their position.  Too bad Dijkstra\'s article has virtually <em>nothing</em> to do with the way <code>goto</code> statements are used these days and thus what the article says has little to no applicability to the modern programming scene.  The <code>goto</code>-less meme verges now on a religion, right down to its scriptures dictated from on high, its high priests and the shunning (or worse) of perceived heretics.</p>\n\n<p>Let\'s put Dijkstra\'s paper into context to shed a little light on the subject.</p>\n\n<p>When Dijkstra wrote his paper the popular languages of the time were unstructured procedural ones like BASIC, FORTRAN (the earlier dialects) and various assembly languages.  It was quite common for people using the higher-level languages to jump <em>all over their code base</em> in twisted, contorted threads of execution that gave rise to the term "spaghetti code".  You can see this by hopping on over to <a href="http://web.archive.org/web/20150215080553/http://www.dunnington.u-net.com/public/startrek/STTR1" rel="noreferrer">the classic Trek game</a> written by Mike Mayfield and trying to figure out how things work.  Take a few moments to look that over.</p>\n\n<p><strong>THIS</strong> is "the unbridled use of the go to statement" that Dijkstra was railing against in his paper in 1968.  <strong>THIS</strong> is the environment he lived in that led him to write that paper.  The ability to jump anywhere you like in your code at any point you liked was what he was criticising and demanding be stopped.  Comparing that to the anaemic powers of <code>goto</code> in C or other such more modern languages is simply risible.</p>\n\n<p>I can already hear the raised chants of the cultists as they face the heretic.  "But," they will chant, "you can make code very difficult to read with <code>goto</code> in C."  Oh yeah?  You can make code very difficult to read without <code>goto</code> as well.  Like this one:</p>\n\n<pre><code>#define _ -F&lt;00||--F-OO--;\nint F=00,OO=00;main(){F_OO();printf("%1.3f\\n",4.*-F/OO/OO);}F_OO()\n{\n            _-_-_-_\n       _-_-_-_-_-_-_-_-_\n    _-_-_-_-_-_-_-_-_-_-_-_\n  _-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n  _-_-_-_-_-_-_-_-_-_-_-_-_-_\n    _-_-_-_-_-_-_-_-_-_-_-_\n        _-_-_-_-_-_-_-_\n            _-_-_-_\n}\n</code></pre>\n\n<p>Not a <code>goto</code> in sight, so it must be easy to read, right?  Or how about this one:</p>\n\n<pre><code>a[900];     b;c;d=1     ;e=1;f;     g;h;O;      main(k,\nl)char*     *l;{g=      atoi(*      ++l);       for(k=\n0;k*k&lt;      g;b=k       ++&gt;&gt;1)      ;for(h=     0;h*h&lt;=\ng;++h);     --h;c=(     (h+=g&gt;h     *(h+1))     -1)&gt;&gt;1;\nwhile(d     &lt;=g){       ++O;for     (f=0;f&lt;     O&amp;&amp;d&lt;=g\n;++f)a[     b&lt;&lt;5|c]     =d++,b+=    e;for(      f=0;f&lt;O\n&amp;&amp;d&lt;=g;     ++f)a[b     &lt;&lt;5|c]=     d++,c+=     e;e= -e\n;}for(c     =0;c&lt;h;     ++c){       for(b=0     ;b&lt;k;++\nb){if(b     &lt;k/2)a[     b&lt;&lt;5|c]     ^=a[(k      -(b+1))\n&lt;&lt;5|c]^=    a[b&lt;&lt;5      |c]^=a[     (k-(b+1     ))&lt;&lt;5|c]\n;printf(    a[b&lt;&lt;5|c    ]?"%-4d"    :"    "     ,a[b&lt;&lt;5\n|c]);}      putchar(    \'\\n\');}}    /*Mike      Laman*/\n</code></pre>\n\n<p>No <code>goto</code> there either.  It must therefore be readable.</p>\n\n<p>What\'s my point with these examples?  It\'s not language features that make unreadable, unmaintainable code.  It\'s not syntax that does it.  It\'s bad programmers that cause this.  And bad programmers, as you can see in that above item, can make <strong>any</strong> language feature unreadable and unusable.  Like the <code>for</code> loops up there.  (You can see them, right?)</p>\n\n<p>Now to be fair, some language constructs are easier to abuse than others.  If you\'re a C programmer, however, I\'d peer far more closely at about 50% of the uses of <code>#define</code> long before I\'d go on a crusade against <code>goto</code>!</p>\n\n<p>So, for those who\'ve bothered to read this far, there are several key points to note.</p>\n\n<ol>\n<li>Dijkstra\'s paper on <code>goto</code> statements was written for a programming environment where <code>goto</code> was a <em>lot</em>\nmore potentially damaging than it is in most modern languages that aren\'t an assembler.</li>\n<li>Automatically throwing away all uses of <code>goto</code> because of this is about as rational as saying "I tried\nto have fun once but didn\'t like it so now I\'m against it".</li>\n<li>There are legitimate uses of the modern (anaemic) <code>goto</code> statements in code that cannot be adequately\nreplaced by other constructs.</li>\n<li>There are, of course, illegitimate uses of the same statements.</li>\n<li>There are, too, illegitimate uses of the modern control statements like the "<code>godo</code>" abomination where an always-false <code>do</code> loop is broken out of using <code>break</code> in place of a <code>goto</code>.  These are often worse than judicious use of <code>goto</code>.</li>\n</ol>\n'}, {'answer_id': 2810495, 'author': 'Sandy', 'author_id': 338240, 'author_profile': 'https://Stackoverflow.com/users/338240', 'pm_score': 2, 'selected': False, 'text': '<p>I find the do{} while(false) usage utterly revolting. It is conceivable might convince me it is necessary in some odd case, but never that it is clean sensible code.</p>\n\n<p>If you must do some such loop, why not make the dependence on the flag variable explicit?</p>\n\n<pre><code>for (stepfailed=0 ; ! stepfailed ; /*empty*/)\n</code></pre>\n'}, {'answer_id': 8726959, 'author': 'pocjoc', 'author_id': 357960, 'author_profile': 'https://Stackoverflow.com/users/357960', 'pm_score': 2, 'selected': False, 'text': '<p>The GOTO can be used, of course, but there is one more important thing than the code style, or if the code is or not readable that you must have in mind when you use it: <strong>the code inside may not be as robust as you think</strong>.<br></p>\n\n<p>For instance, look at the following two code snippets:</p>\n\n<pre><code>If A &lt;&gt; 0 Then A = 0 EndIf\nWrite("Value of A:" + A)\n</code></pre>\n\n<p>An equivalent code with GOTO</p>\n\n<pre><code>If A == 0 Then GOTO FINAL EndIf\n   A = 0\nFINAL:\nWrite("Value of A:" + A)\n</code></pre>\n\n<p>The first thing we think is that the result of both bits of code will be that "Value of A: 0" (we suppose an execution without parallelism, of course)</p>\n\n<p>That\'s not correct: in the first sample, A will always be 0, but in the second sample (with the GOTO statement) A might not be 0. Why?</p>\n\n<p>The reason is because from another point of the program I can insert a <code>GOTO FINAL</code> without controlling the value of A.</p>\n\n<p>This example is very obvious, but as programs get more complicated, the difficulty of seeing those kind of things increases.</p>\n\n<p>Related material can be found into the famous article from Mr. Dijkstra <a href="http://www.cs.utexas.edu/users/EWD/ewd02xx/EWD215.PDF" rel="nofollow">"A case against the GO TO statement"</a> </p>\n'}, {'answer_id': 20081648, 'author': 'Nuclear', 'author_id': 935512, 'author_profile': 'https://Stackoverflow.com/users/935512', 'pm_score': 1, 'selected': False, 'text': '<p>I use goto in the following case:\nwhen needed to return from funcions at different places, and before return some uninitialization needs to be done:</p>\n\n<p>non-goto version:</p>\n\n<pre><code>int doSomething (struct my_complicated_stuff *ctx)    \n{\n    db_conn *conn;\n    RSA *key;\n    char *temp_data;\n    conn = db_connect();  \n\n\n    if (ctx-&gt;smth-&gt;needs_alloc) {\n      temp_data=malloc(ctx-&gt;some_size);\n      if (!temp_data) {\n        db_disconnect(conn);\n        return -1;      \n        }\n    }\n\n    ...\n\n    if (!ctx-&gt;smth-&gt;needs_to_be_processed) {\n        free(temp_data);    \n        db_disconnect(conn);    \n        return -2;\n    }\n\n    pthread_mutex_lock(ctx-&gt;mutex);\n\n    if (ctx-&gt;some_other_thing-&gt;error) {\n        pthread_mutex_unlock(ctx-&gt;mutex);\n        free(temp_data);\n        db_disconnect(conn);        \n        return -3;  \n    }\n\n    ...\n\n    key=rsa_load_key(....);\n\n    ...\n\n    if (ctx-&gt;something_else-&gt;error) {\n         rsa_free(key); \n         pthread_mutex_unlock(ctx-&gt;mutex);\n         free(temp_data);\n         db_disconnect(conn);       \n         return -4;  \n    }\n\n    if (ctx-&gt;something_else-&gt;additional_check) {\n         rsa_free(key); \n         pthread_mutex_unlock(ctx-&gt;mutex);\n         free(temp_data);\n         db_disconnect(conn);       \n         return -5;  \n    }\n\n\n    pthread_mutex_unlock(ctx-&gt;mutex);\n    free(temp_data);    \n    db_disconnect(conn);    \n    return 0;     \n}\n</code></pre>\n\n<p>goto version:</p>\n\n<pre><code>int doSomething_goto (struct my_complicated_stuff *ctx)\n{\n    int ret=0;\n    db_conn *conn;\n    RSA *key;\n    char *temp_data;\n    conn = db_connect();  \n\n\n    if (ctx-&gt;smth-&gt;needs_alloc) {\n      temp_data=malloc(ctx-&gt;some_size);\n      if (!temp_data) {\n            ret=-1;\n           goto exit_db;   \n          }\n    }\n\n    ...\n\n    if (!ctx-&gt;smth-&gt;needs_to_be_processed) {\n        ret=-2;\n        goto exit_freetmp;      \n    }\n\n    pthread_mutex_lock(ctx-&gt;mutex);\n\n    if (ctx-&gt;some_other_thing-&gt;error) {\n        ret=-3;\n        goto exit;  \n    }\n\n    ...\n\n    key=rsa_load_key(....);\n\n    ...\n\n    if (ctx-&gt;something_else-&gt;error) {\n        ret=-4;\n        goto exit_freekey; \n    }\n\n    if (ctx-&gt;something_else-&gt;additional_check) {\n        ret=-5;\n        goto exit_freekey;  \n    }\n\nexit_freekey:\n    rsa_free(key);\nexit:    \n    pthread_mutex_unlock(ctx-&gt;mutex);\nexit_freetmp:\n    free(temp_data);        \nexit_db:\n    db_disconnect(conn);    \n    return ret;     \n}\n</code></pre>\n\n<p>The second version makes it easier, when you need to change something in the deallocation statements (each is used once in the code), and reduces the chance to skip any of them, when adding a new branch. Moving them in a function will not help here, because the deallocation can be done at different "levels". </p>\n'}, {'answer_id': 20887535, 'author': 'nhcohen', 'author_id': 2395478, 'author_profile': 'https://Stackoverflow.com/users/2395478', 'pm_score': 3, 'selected': False, 'text': '<p>The most thoughtful and thorough discussion of goto statements, their legitimate uses, and alternative constructs that can be used in place of "virtuous goto statements" but can be abused as easily as goto statements, is Donald Knuth\'s article "<a href="http://delivery.acm.org/10.1145/360000/356640/p261-knuth.pdf?ip=216.239.45.90&amp;id=356640&amp;acc=ACTIVE%20SERVICE&amp;key=4D4702B0C3E38B35B1A2F845BC253D7142744268AEEA849682EF35FD85DCD9E9&amp;CFID=389578097&amp;CFTOKEN=41499978&amp;__acm__=1388680055_c32b25b15539895440b9901c898a9dec" rel="noreferrer">Structured Programming with goto Statements</a>", in the December 1974 Computing Surveys (volume 6, no. 4. pp. 261 - 301).</p>\n\n<p>Not surprisingly, some aspects of this 39-year old paper are dated: Orders-of-magnitude increases in processing power make some of Knuth\'s performance improvements unnoticeable for moderately sized problems, and new programming-language constructs have been invented since then. (For example, try-catch blocks subsume Zahn\'s Construct, although they are rarely used in that way.) But Knuth covers all sides of the argument, and should be required reading before anyone rehashes the issue yet again.</p>\n'}, {'answer_id': 21360087, 'author': 'herohuyongtao', 'author_id': 2589776, 'author_profile': 'https://Stackoverflow.com/users/2589776', 'pm_score': 3, 'selected': False, 'text': '<p>Take a look at <a href="http://www.cprogramming.com/tutorial/goto.html" rel="noreferrer">When To Use Goto When Programming in C</a>:</p>\n<blockquote>\n<p>Although the use of goto is almost always bad programming practice (surely you can find a better way of doing XYZ), there are times when it really isn\'t a bad choice. Some might even argue that, when it is useful, it\'s the best choice.</p>\n<p>Most of what I have to say about goto really only applies to C. If you\'re using C++, there\'s no sound reason to use goto in place of exceptions. In C, however, you don\'t have the power of an exception handling mechanism, so if you want to separate out error handling from the rest of your program logic, and you want to avoid rewriting clean up code multiple times throughout your code, then goto can be a good choice.</p>\n</blockquote>\n<p>What do I mean? You might have some code that looks like this:</p>\n<pre><code>int big_function()\n{\n    /* do some work */\n    if([error])\n    {\n        /* clean up*/\n        return [error];\n    }\n    /* do some more work */\n    if([error])\n    {\n        /* clean up*/\n        return [error];\n    }\n    /* do some more work */\n    if([error])\n    {\n        /* clean up*/\n        return [error];\n    }\n    /* do some more work */\n    if([error])\n    {\n        /* clean up*/\n        return [error];\n    }\n    /* clean up*/\n    return [success];\n}\n</code></pre>\n<p>This is fine until you realize that you need to change your cleanup code. Then you have to go through and make 4 changes. Now, you might decide that you can just encapsulate all of the cleanup into a single function; that\'s not a bad idea. But it does mean that you\'ll need to be careful with pointers -- if you plan to free a pointer in your cleanup function, there\'s no way to set it to then point to NULL unless you pass in a pointer to a pointer. In a lot of cases, you won\'t be using that pointer again anyway, so that may not be a major concern. On the other hand, if you add in a new pointer, file handle, or other thing that needs cleanup, then you\'ll need to change your cleanup function again; and then you\'ll need to change the arguments to that function.</p>\n<p>By using <code>goto</code>, it will be</p>\n<pre><code>int big_function()\n{\n    int ret_val = [success];\n    /* do some work */\n    if([error])\n    {\n        ret_val = [error];\n        goto end;\n    }\n    /* do some more work */\n    if([error])\n    {\n        ret_val = [error];\n        goto end;\n    }\n    /* do some more work */\n    if([error])\n    {\n        ret_val = [error];\n        goto end;\n    }\n    /* do some more work */\n    if([error])\n    {\n        ret_val = [error];\n        goto end;\n    }\nend:\n    /* clean up*/\n    return ret_val;\n}\n</code></pre>\n<p>The benefit here is that your code following end has access to everything it will need to perform cleanup, and you\'ve managed to reduce the number of change points considerably. Another benefit is that you\'ve gone from having multiple exit points for your function to just one; there\'s no chance you\'ll accidentally return from the function without cleaning up.</p>\n<p>Moreover, since goto is only being used to jump to a single point, it\'s not as though you\'re creating a mass of spaghetti code jumping back and forth in an attempt to simulate function calls. Rather, goto actually helps write more structured code.</p>\n<hr />\n<p><strong>In a word, <code>goto</code> should always be used sparingly, and as a last resort -- but there is a time and a place for it. The question should be not &quot;do you have to use it&quot; but &quot;is it the best choice&quot; to use it.</strong></p>\n'}, {'answer_id': 24730841, 'author': 'Fizz', 'author_id': 3588161, 'author_profile': 'https://Stackoverflow.com/users/3588161', 'pm_score': 2, 'selected': False, 'text': '<p>1) The most common use of goto that I know of is emulating exception handling in languages that don\'t offer it, namely in C. (The code given by Nuclear above is just that.) Look at the Linux source code and you\'ll see a bazillion gotos used that way; there were about 100,000 gotos in Linux code according to a quick survey conducted in 2013: <a href="http://blog.regehr.org/archives/894" rel="nofollow">http://blog.regehr.org/archives/894</a>. Goto usage is even mentioned in the Linux coding style guide: <a href="https://www.kernel.org/doc/Documentation/CodingStyle" rel="nofollow">https://www.kernel.org/doc/Documentation/CodingStyle</a>. Just like object-oriented programming is emulated using structs populated with function pointers, goto has its place in C programming. So who is right: Dijkstra or Linus (and all Linux kernel coders)? It\'s theory vs. practice basically.</p>\n\n<p>There is however the usual gotcha for not having compiler-level support and checks for common constructs/patterns: it\'s easier to use them wrong and introduce bugs without compile-time checks. Windows and Visual C++ but in C mode offer exception handling via SEH/VEH for this very reason: exceptions are useful even outside OOP languages, i.e. in a procedural language. But the compiler can\'t always save your bacon, even if it offers syntactic support for exceptions in the language. Consider as example of the latter case the famous Apple SSL "goto fail" bug, which just duplicated one goto with disastrous consequences (<a href="https://www.imperialviolet.org/2014/02/22/applebug.html" rel="nofollow">https://www.imperialviolet.org/2014/02/22/applebug.html</a>):</p>\n\n<pre><code>if (something())\n  goto fail;\n  goto fail; // copypasta bug\nprintf("Never reached\\n");\nfail:\n  // control jumps here\n</code></pre>\n\n<p>You can have exactly the same bug using compiler-supported exceptions, e.g. in C++:</p>\n\n<pre><code>struct Fail {};\n\ntry {\n  if (something())\n    throw Fail();\n    throw Fail(); // copypasta bug\n  printf("Never reached\\n");\n}\ncatch (Fail&amp;) {\n  // control jumps here\n}\n</code></pre>\n\n<p>But both variants of the bug can be avoided if the compiler analyzes and warns you about unreachable code. For example compiling with Visual C++ at the /W4 warning level finds the bug in both cases. Java for instance forbids unreachable code (where it can find it!) for a pretty good reason: it\'s likely to be a bug in the average Joe\'s code. As long as the goto construct doesn\'t allow targets that the compiler can\'t easily figure out, like gotos to computed addresses(**), it\'s not any harder for the compiler to find unreachable code inside a function with gotos than using Dijkstra-approved code.</p>\n\n<p>(**) Footnote: Gotos to computed line numbers are possible in some versions of Basic, e.g. GOTO 10*x where x is a variable. Rather confusingly, in Fortran "computed goto" refers to a construct that is equivalent to a switch statement in C. Standard C doesn\'t allow computed gotos in the language, but only gotos to statically/syntactically declared labels. GNU C however has an extension to get the address of a label (the unary, prefix &amp;&amp; operator) and also allows a goto to a variable of type void*. See <a href="https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html" rel="nofollow">https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html</a> for more on this obscure sub-topic. The rest of this post ins\'t concerned with that obscure GNU C feature.</p>\n\n<p>Standard C (i.e. not computed) gotos are not usually the reason why unreachable code can\'t be found at compile time. The usual reason is logic code like the following. Given</p>\n\n<pre><code>int computation1() {\n  return 1;\n}\n\nint computation2() {\n  return computation1();\n}\n</code></pre>\n\n<p>It\'s just as hard for a compiler to find unreachable code in any of the following 3 constructs:</p>\n\n<pre><code>void tough1() {\n  if (computation1() != computation2())\n    printf("Unreachable\\n");\n}\n\nvoid tough2() {\n  if (computation1() == computation2())\n    goto out;\n  printf("Unreachable\\n");\nout:;\n}\n\nstruct Out{};\n\nvoid tough3() {\n  try {\n    if (computation1() == computation2())\n      throw Out();\n    printf("Unreachable\\n");\n  }\n  catch (Out&amp;) {\n  }\n}\n</code></pre>\n\n<p>(Excuse my brace-related coding style, but I tried to keep the examples as compact as possible.)</p>\n\n<p>Visual C++ /W4 (even with /Ox) fails to find unreachable code in any of these, and as you probably know the problem of finding unreachable code is undecidable in general. (If you don\'t believe me about that: <a href="https://www.cl.cam.ac.uk/teaching/2006/OptComp/slides/lecture02.pdf" rel="nofollow">https://www.cl.cam.ac.uk/teaching/2006/OptComp/slides/lecture02.pdf</a>)</p>\n\n<p>As a related issue, the C goto can be used to emulate exceptions only inside the body of a function. The standard C library offers a setjmp() and longjmp() pair of functions for emulating non-local exits/exceptions, but those have some serious drawbacks compared to what other languages offer. The Wikipedia article <a href="http://en.wikipedia.org/wiki/Setjmp.h" rel="nofollow">http://en.wikipedia.org/wiki/Setjmp.h</a> explains fairly well this latter issue. This function pair also works on Windows (<a href="http://msdn.microsoft.com/en-us/library/yz2ez4as.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/yz2ez4as.aspx</a>), but hardly anyone uses them there because SEH/VEH is superior. Even on Unix, I think setjmp and longjmp are very seldom used. </p>\n\n<p>2) I think the second most common use of goto in C is implementing multi-level break or multi-level continue, which is also a fairly uncontroversial use case. Recall that Java doesn\'t allow goto label, but allows break label or continue label. According to <a href="http://www.oracle.com/technetwork/java/simple-142616.html" rel="nofollow">http://www.oracle.com/technetwork/java/simple-142616.html</a>, this is actually the most common use case of gotos in C (90% they say), but in my subjective experience, system code tends to use gotos for error handling more often. Perhaps in scientific code or where the OS offers exception handling (Windows) then multi-level exits are the dominant use case. They don\'t really give any details as to the context of their survey.</p>\n\n<p>Edited to add: it turns out these two use patterns are found in the C book of Kernighan and Ritchie, around page 60 (depending on edition). Another thing of note is that both use cases involve only forward gotos. And it turns out that MISRA C 2012 edition (unlike the 2004 edition) now permits gotos, as long as they are only forward ones.</p>\n'}, {'answer_id': 40031837, 'author': 'Jan Turoň', 'author_id': 343721, 'author_profile': 'https://Stackoverflow.com/users/343721', 'pm_score': 3, 'selected': False, 'text': '<p>Some say there is no reason for goto in C++. Some say that in 99% cases there are better alternatives. <strong>This is not reasoning, just irrational impressions.</strong> Here\'s a solid example where goto leads to a nice code, something like enhanced do-while loop:</p>\n\n<pre><code>int i;\n\nPROMPT_INSERT_NUMBER:\n  std::cout &lt;&lt; "insert number: ";\n  std::cin &gt;&gt; i;\n  if(std::cin.fail()) {\n    std::cin.clear();\n    std::cin.ignore(1000,\'\\n\');\n    goto PROMPT_INSERT_NUMBER;          \n  }\n\nstd::cout &lt;&lt; "your number is " &lt;&lt; i;\n</code></pre>\n\n<p>Compare it to goto-free code:</p>\n\n<pre><code>int i;\n\nbool loop;\ndo {\n  loop = false;\n  std::cout &lt;&lt; "insert number: ";\n  std::cin &gt;&gt; i;\n  if(std::cin.fail()) {\n    std::cin.clear();\n    std::cin.ignore(1000,\'\\n\');\n    loop = true;          \n  }\n} while(loop);\n\nstd::cout &lt;&lt; "your number is " &lt;&lt; i;\n</code></pre>\n\n<p>I see these differences:</p>\n\n<ul>\n<li>nested <code>{}</code> block is needed (albeit <code>do {...} while</code> looks more familiar)</li>\n<li>extra <code>loop</code> variable is needed, used in four places</li>\n<li>it takes longer time to read and understand the work with the <code>loop</code></li>\n<li>the <code>loop</code> does not hold any data, it just controls the flow of the execution, which is less comprehensible than simple label</li>\n</ul>\n\n<p>There is another example</p>\n\n<pre><code>void sort(int* array, int length) {\nSORT:\n  for(int i=0; i&lt;length-1; ++i) if(array[i]&gt;array[i+1]) {\n    swap(data[i], data[i+1]);\n    goto SORT; // it is very easy to understand this code, right?\n  }\n}\n</code></pre>\n\n<p>Now let\'s get rid of the "evil" goto:</p>\n\n<pre><code>void sort(int* array, int length) {\n  bool seemslegit;\n  do {\n    seemslegit = true;\n    for(int i=0; i&lt;length-1; ++i) if(array[i]&gt;array[i+1]) {\n      swap(data[i], data[i+1]);\n      seemslegit = false;\n    }\n  } while(!seemslegit);\n}\n</code></pre>\n\n<p>You see it is the same type of using goto, it is well structured pattern and it is not forward goto as many promote as the only recommended way. Surely you want to avoid "smart" code like this:</p>\n\n<pre><code>void sort(int* array, int length) {\n  for(int i=0; i&lt;length-1; ++i) if(array[i]&gt;array[i+1]) {\n    swap(data[i], data[i+1]);\n    i = -1; // it works, but WTF on the first glance\n  }\n}\n</code></pre>\n\n<p>The point is that goto can be easily misused, but goto itself is not to blame. Note that label has function scope in C++, so it does not pollute global scope like in pure assembly, in which <em>overlapping loops</em> have its place and are very common - like in the following code for 8051, where 7segment display is connected to P1. The program loops lightning segment around:</p>\n\n<pre><code>; P1 states loops\n; 11111110 &lt;-\n; 11111101  |\n; 11111011  |\n; 11110111  |\n; 11101111  |\n; 11011111  |\n; |_________|\n\ninit_roll_state:\n    MOV P1,#11111110b\n    ACALL delay\nnext_roll_state:\n    MOV A,P1\n    RL A\n    MOV P1,A\n    ACALL delay\n    JNB P1.5, init_roll_state\n    SJMP next_roll_state\n</code></pre>\n\n<p>There is another advantage: goto can serve as named loops, conditions and other flows:</p>\n\n<pre><code>if(valid) {\n  do { // while(loop)\n\n// more than one page of code here\n// so it is better to comment the meaning\n// of the corresponding curly bracket\n\n  } while(loop);\n} // if(valid)\n</code></pre>\n\n<p>Or you can use equivalent goto with indentation, so you don\'t need comment if you choose the label name wisely:</p>\n\n<pre><code>if(!valid) goto NOTVALID;\n  LOOPBACK:\n\n// more than one page of code here\n\n  if(loop) goto LOOPBACK;\nNOTVALID:;\n</code></pre>\n'}, {'answer_id': 57281180, 'author': 'Beefster', 'author_id': 5079779, 'author_profile': 'https://Stackoverflow.com/users/5079779', 'pm_score': 2, 'selected': False, 'text': "<p>It comes in handy for character-wise string processing from time to time.</p>\n\n<p>Imagine something like this printf-esque example:</p>\n\n<pre><code>for cur_char, next_char in sliding_window(input_string) {\n    if cur_char == '%' {\n        if next_char == '%' {\n            cur_char_index += 1\n            goto handle_literal\n        }\n        # Some additional logic\n        if chars_should_be_handled_literally() {\n            goto handle_literal\n        }\n        # Handle the format\n    }\n    # some other control characters\n    else {\n      handle_literal:\n        # Complicated logic here\n        # Maybe it's writing to an array for some OpenGL calls later or something,\n        # all while modifying a bunch of local variables declared outside the loop\n    }\n}\n</code></pre>\n\n<p>You could refactor that <code>goto handle_literal</code> to a function call, but if it's modifying several different local variables, you'd have to pass references to each unless your language supports mutable closures. You'd still have to use a <code>continue</code> statement (which is arguably a form of goto) after the call to get the same semantics if your logic makes an else case not work.</p>\n\n<p>I have also used gotos judiciously in lexers, typically for similar cases. You don't need them most of the time, but they're nice to have for those weird cases.</p>\n"}, {'answer_id': 64478049, 'author': 'bask185', 'author_id': 8477952, 'author_profile': 'https://Stackoverflow.com/users/8477952', 'pm_score': 3, 'selected': False, 'text': '<p>I have come across a situation where a <code>goto</code> was a good solution, and I have not seen this example here or anywhere.</p>\n<p>I had a switch case with a few cases which all needed to call the same function in the end. I had other cases which all needed to call a different function in the end.</p>\n<p>This looked a bit like this:</p>\n<pre><code>switch( x ) {\n    \n    case 1: case1() ; doStuffFor123() ; break ;\n    case 2: case2() ; doStuffFor123() ; break ;\n    case 3: case3() ; doStuffFor123() ; break ;\n    \n    case 4: case4() ; doStuffFor456() ; break ;\n    case 5: case5() ; doStuffFor456() ; break ;\n    case 6: case6() ; doStuffFor456() ; break ;\n    \n    case 7: case7() ; doStuffFor789() ; break ;\n    case 8: case8() ; doStuffFor789() ; break ;\n    case 9: case9() ; doStuffFor789() ; break ;\n}\n</code></pre>\n<p>Instead of giving every case a function call, I replaced the <code>break</code> by a <code>goto</code>. The <code>goto</code> jumps to a label which is also inside the switch case.</p>\n<pre><code>switch( x ) {\n    \n    case 1: case1() ; goto stuff123 ;\n    case 2: case2() ; goto stuff123 ;\n    case 3: case3() ; goto stuff123 ;\n    \n    case 4: case4() ; goto stuff456 ;\n    case 5: case5() ; goto stuff456 ;\n    case 6: case6() ; goto stuff456 ;\n    \n    case 7: case7() ; goto stuff789 ;\n    case 8: case8() ; goto stuff789 ;\n    case 9: case9() ; goto stuff789 ;\n    \n    stuff123: doStuffFor123() ; break ;\n    stuff456: doStuffFor456() ; break ;\n    stuff789: doStuffFor789() ; break ;\n}\n</code></pre>\n<p>cases 1 through 3 all must call <code>doStuffFor123()</code> and similarly cases 4 through 6 had to call <code>doStuffFor456()</code> etc.</p>\n<p>In my opinion, gotos are perfectly fine if you use them correctly. In the end, any code is as clear as people write it. With gotos one can make spaghetti code, but that does not mean that gotos are the cause of the spaghetti code. That cause is us; programmers. I can also create spaghetti code with functions if I want to. The same goes for macros as well.</p>\n'}, {'answer_id': 73454644, 'author': 'Kellad', 'author_id': 2428778, 'author_profile': 'https://Stackoverflow.com/users/2428778', 'pm_score': 0, 'selected': False, 'text': "<p>Use &quot;goto&quot; wherever it makes your code more readable or run faster. Just don't let it turn your code into spaghetti.</p>\n"}]
['https://Stackoverflow.com/questions/24451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1597/']