| 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 |
| 10 |
<https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es76-avoid-goto>`_ |
| 11 |
from the C++ Core Guidelines and |
| 12 |
`6.3.1 <https://www.perforce.com/resources/qac/high-integrity-cpp-coding-standard/statements>`_ |
| 13 |
from High Integrity C++ Coding Standard. |
| 14 |
|
| 15 |
For more information on why to avoid programming |
| 16 |
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>`_. |
| 17 |
|
| 18 |
The check diagnoses ``goto`` for backward jumps in every language mode. These |
| 19 |
should 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 |
|
| 38 |
Modern 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 |
|
| 52 |
All other uses of ``goto`` are diagnosed in `C++`. |