xref: /llvm-project/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-goto.rst (revision 0f1f1d45c9f77bf5d8e5dce32551b7c78772b8a6)
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
10<https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es76-avoid-goto>`_
11from the C++ Core Guidelines and
12`6.3.1 <https://www.perforce.com/resources/qac/high-integrity-cpp-coding-standard/statements>`_
13from High Integrity C++ Coding Standard.
14
15For more information on why to avoid programming
16with ``goto`` you can read the famous paper `A Case against the GO TO Statement. <https://www.cs.utexas.edu/users/EWD/ewd02xx/EWD215.PDF>`_.
17
18The check diagnoses ``goto`` for backward jumps in every language mode. These
19should be replaced with `C/C++` looping constructs.
20
21.. code-block:: c++
22
23  // Bad, handwritten for loop.
24  int i = 0;
25  // Jump label for the loop
26  loop_start:
27  do_some_operation();
28
29  if (i < 100) {
30    ++i;
31    goto loop_start;
32  }
33
34  // Better
35  for(int i = 0; i < 100; ++i)
36    do_some_operation();
37
38Modern C++ needs ``goto`` only to jump out of nested loops.
39
40.. code-block:: c++
41
42  for(int i = 0; i < 100; ++i) {
43    for(int j = 0; j < 100; ++j) {
44      if (i * j > 500)
45        goto early_exit;
46    }
47  }
48
49  early_exit:
50  some_operation();
51
52All other uses of ``goto`` are diagnosed in `C++`.
53