xref: /llvm-project/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-goto.rst (revision 0f1f1d45c9f77bf5d8e5dce32551b7c78772b8a6)
16e566bc5SRichard.. title:: clang-tidy - cppcoreguidelines-avoid-goto
26e566bc5SRichard
36e566bc5SRichardcppcoreguidelines-avoid-goto
46e566bc5SRichard============================
56e566bc5SRichard
66e566bc5SRichardThe usage of ``goto`` for control flow is error prone and should be replaced
76e566bc5SRichardwith looping constructs. Only forward jumps in nested loops are accepted.
86e566bc5SRichard
9*0f1f1d45SPiotr ZegarThis check implements `ES.76
10*0f1f1d45SPiotr Zegar<https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es76-avoid-goto>`_
11*0f1f1d45SPiotr Zegarfrom the C++ Core Guidelines and
12*0f1f1d45SPiotr Zegar`6.3.1 <https://www.perforce.com/resources/qac/high-integrity-cpp-coding-standard/statements>`_
13*0f1f1d45SPiotr Zegarfrom High Integrity C++ Coding Standard.
146e566bc5SRichard
156e566bc5SRichardFor more information on why to avoid programming
166e566bc5SRichardwith ``goto`` you can read the famous paper `A Case against the GO TO Statement. <https://www.cs.utexas.edu/users/EWD/ewd02xx/EWD215.PDF>`_.
176e566bc5SRichard
186e566bc5SRichardThe check diagnoses ``goto`` for backward jumps in every language mode. These
196e566bc5SRichardshould be replaced with `C/C++` looping constructs.
206e566bc5SRichard
216e566bc5SRichard.. code-block:: c++
226e566bc5SRichard
236e566bc5SRichard  // Bad, handwritten for loop.
246e566bc5SRichard  int i = 0;
256e566bc5SRichard  // Jump label for the loop
266e566bc5SRichard  loop_start:
276e566bc5SRichard  do_some_operation();
286e566bc5SRichard
296e566bc5SRichard  if (i < 100) {
306e566bc5SRichard    ++i;
316e566bc5SRichard    goto loop_start;
326e566bc5SRichard  }
336e566bc5SRichard
346e566bc5SRichard  // Better
356e566bc5SRichard  for(int i = 0; i < 100; ++i)
366e566bc5SRichard    do_some_operation();
376e566bc5SRichard
386e566bc5SRichardModern C++ needs ``goto`` only to jump out of nested loops.
396e566bc5SRichard
406e566bc5SRichard.. code-block:: c++
416e566bc5SRichard
426e566bc5SRichard  for(int i = 0; i < 100; ++i) {
436e566bc5SRichard    for(int j = 0; j < 100; ++j) {
446e566bc5SRichard      if (i * j > 500)
456e566bc5SRichard        goto early_exit;
466e566bc5SRichard    }
476e566bc5SRichard  }
486e566bc5SRichard
496e566bc5SRichard  early_exit:
506e566bc5SRichard  some_operation();
516e566bc5SRichard
526e566bc5SRichardAll other uses of ``goto`` are diagnosed in `C++`.
53