fcb7dd313259c91fe08a1f3b6739e76db64eabd9
[platform/upstream/llvm.git] / clang-tools-extra / docs / clang-tidy / checks / cppcoreguidelines-avoid-goto.rst
1 .. title:: clang-tidy - cppcoreguidelines-avoid-goto
2
3 cppcoreguidelines-avoid-goto
4 ============================
5
6 The usage of ``goto`` for control flow is error prone and should be replaced
7 with looping constructs. Only forward jumps in nested loops are accepted.
8
9 This check implements `ES.76 <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es76-avoid-goto>`_ 
10 from 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
13 For more information on why to avoid programming 
14 with ``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
16 The check diagnoses ``goto`` for backward jumps in every language mode. These
17 should 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
36 Modern 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
50 All other uses of ``goto`` are diagnosed in `C++`.