1.. title:: clang-tidy - cppcoreguidelines-avoid-goto
2
3cppcoreguidelines-avoid-goto
4============================
5
6The usage of ``goto`` for control flow is error prone and should be replaced
7with looping constructs. Only forward jumps in nested loops are accepted.
8
9This check implements `ES.76 <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es76-avoid-goto>`_
10from the CppCoreGuidelines and
11`6.3.1 from High Integrity C++ <http://www.codingstandard.com/rule/6-3-1-ensure-that-the-labels-for-a-jump-statement-or-a-switch-condition-appear-later-in-the-same-or-an-enclosing-block/>`_.
12
13For more information on why to avoid programming
14with ``goto`` you can read the famous paper `A Case against the GO TO Statement. <https://www.cs.utexas.edu/users/EWD/ewd02xx/EWD215.PDF>`_.
15
16The check diagnoses ``goto`` for backward jumps in every language mode. These
17should be replaced with `C/C++` looping constructs.
18
19.. code-block:: c++
20
21  // Bad, handwritten for loop.
22  int i = 0;
23  // Jump label for the loop
24  loop_start:
25  do_some_operation();
26
27  if (i < 100) {
28    ++i;
29    goto loop_start;
30  }
31
32  // Better
33  for(int i = 0; i < 100; ++i)
34    do_some_operation();
35
36Modern C++ needs ``goto`` only to jump out of nested loops.
37
38.. code-block:: c++
39
40  for(int i = 0; i < 100; ++i) {
41    for(int j = 0; j < 100; ++j) {
42      if (i * j > 500)
43        goto early_exit;
44    }
45  }
46
47  early_exit:
48  some_operation();
49
50All other uses of ``goto`` are diagnosed in `C++`.
51