1.. title:: clang-tidy - bugprone-redundant-branch-condition 2 3bugprone-redundant-branch-condition 4=================================== 5 6Finds condition variables in nested ``if`` statements that were also checked in 7the outer ``if`` statement and were not changed. 8 9Simple example: 10 11.. code-block:: c 12 13 bool onFire = isBurning(); 14 if (onFire) { 15 if (onFire) 16 scream(); 17 } 18 19Here `onFire` is checked both in the outer ``if`` and the inner ``if`` statement 20without a possible change between the two checks. The check warns for this code 21and suggests removal of the second checking of variable `onFire`. 22 23The checker also detects redundant condition checks if the condition variable 24is an operand of a logical "and" (``&&``) or a logical "or" (``||``) operator: 25 26.. code-block:: c 27 28 bool onFire = isBurning(); 29 if (onFire) { 30 if (onFire && peopleInTheBuilding > 0) 31 scream(); 32 } 33 34.. code-block:: c 35 36 bool onFire = isBurning(); 37 if (onFire) { 38 if (onFire || isCollapsing()) 39 scream(); 40 } 41 42In the first case (logical "and") the suggested fix is to remove the redundant 43condition variable and keep the other side of the ``&&``. In the second case 44(logical "or") the whole ``if`` is removed similarily to the simple case on the 45top. 46 47The condition of the outer ``if`` statement may also be a logical "and" (``&&``) 48expression: 49 50.. code-block:: c 51 52 bool onFire = isBurning(); 53 if (onFire && fireFighters < 10) { 54 if (someOtherCondition()) { 55 if (onFire) 56 scream(); 57 } 58 } 59 60The error is also detected if both the outer statement is a logical "and" 61(``&&``) and the inner statement is a logical "and" (``&&``) or "or" (``||``). 62The inner ``if`` statement does not have to be a direct descendant of the outer 63one. 64 65No error is detected if the condition variable may have been changed between the 66two checks: 67 68.. code-block:: c 69 70 bool onFire = isBurning(); 71 if (onFire) { 72 tryToExtinguish(onFire); 73 if (onFire && peopleInTheBuilding > 0) 74 scream(); 75 } 76 77Every possible change is considered, thus if the condition variable is not 78a local variable of the function, it is a volatile or it has an alias (pointer 79or reference) then no warning is issued. 80 81Known limitations 82^^^^^^^^^^^^^^^^^ 83 84The ``else`` branch is not checked currently for negated condition variable: 85 86.. code-block:: c 87 88 bool onFire = isBurning(); 89 if (onFire) { 90 scream(); 91 } else { 92 if (!onFire) { 93 continueWork(); 94 } 95 } 96 97The checker currently only detects redundant checking of single condition 98variables. More complex expressions are not checked: 99 100.. code-block:: c 101 102 if (peopleInTheBuilding == 1) { 103 if (peopleInTheBuilding == 1) { 104 doSomething(); 105 } 106 } 107