1.. title:: clang-tidy - bugprone-branch-clone 2 3bugprone-branch-clone 4===================== 5 6Checks for repeated branches in ``if/else if/else`` chains, consecutive 7repeated branches in ``switch`` statements and identical true and false 8branches in conditional operators. 9 10.. code-block:: c++ 11 12 if (test_value(x)) { 13 y++; 14 do_something(x, y); 15 } else { 16 y++; 17 do_something(x, y); 18 } 19 20In this simple example (which could arise e.g. as a copy-paste error) the 21``then`` and ``else`` branches are identical and the code is equivalent the 22following shorter and cleaner code: 23 24.. code-block:: c++ 25 26 test_value(x); // can be omitted unless it has side effects 27 y++; 28 do_something(x, y); 29 30 31If this is the intended behavior, then there is no reason to use a conditional 32statement; otherwise the issue can be solved by fixing the branch that is 33handled incorrectly. 34 35The check also detects repeated branches in longer ``if/else if/else`` chains 36where it would be even harder to notice the problem. 37 38In ``switch`` statements the check only reports repeated branches when they are 39consecutive, because it is relatively common that the ``case:`` labels have 40some natural ordering and rearranging them would decrease the readability of 41the code. For example: 42 43.. code-block:: c++ 44 45 switch (ch) { 46 case 'a': 47 return 10; 48 case 'A': 49 return 10; 50 case 'b': 51 return 11; 52 case 'B': 53 return 11; 54 default: 55 return 10; 56 } 57 58Here the check reports that the ``'a'`` and ``'A'`` branches are identical 59(and that the ``'b'`` and ``'B'`` branches are also identical), but does not 60report that the ``default:`` branch is also identical to the first two branches. 61If this is indeed the correct behavior, then it could be implemented as: 62 63.. code-block:: c++ 64 65 switch (ch) { 66 case 'a': 67 case 'A': 68 return 10; 69 case 'b': 70 case 'B': 71 return 11; 72 default: 73 return 10; 74 } 75 76Here the check does not warn for the repeated ``return 10;``, which is good if 77we want to preserve that ``'a'`` is before ``'b'`` and ``default:`` is the last 78branch. 79 80Finally, the check also examines conditional operators and reports code like: 81 82.. code-block:: c++ 83 84 return test_value(x) ? x : x; 85 86Unlike if statements, the check does not detect chains of conditional 87operators. 88 89Note: This check also reports situations where branches become identical only 90after preprocession. 91