brintos

brintos / llvm-project-archived public Read only

0
0
Text · 2.6 KiB · 7a321bd Raw
108 lines · plain
1.. title:: clang-tidy - bugprone-redundant-branch-condition2 3bugprone-redundant-branch-condition4===================================5 6Finds condition variables in nested ``if`` statements that were also checked in7the outer ``if`` statement and were not changed.8 9Simple example:10 11.. code-block:: c12 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``20statement without a possible change between the two checks. The check warns for21this code and suggests removal of the second checking of variable `onFire`.22 23The checker also detects redundant condition checks if the condition variable24is an operand of a logical "and" (``&&``) or a logical "or" (``||``) operator:25 26.. code-block:: c27 28  bool onFire = isBurning();29  if (onFire) {30    if (onFire && peopleInTheBuilding > 0)31      scream();32  }33 34.. code-block:: c35 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 redundant43condition variable and keep the other side of the ``&&``. In the second case44(logical "or") the whole ``if`` is removed similarly to the simple case on the45top.46 47The condition of the outer ``if`` statement may also be a logical "and"48(``&&``) expression:49 50.. code-block:: c51 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 outer63one.64 65No error is detected if the condition variable may have been changed between66the two checks:67 68.. code-block:: c69 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 not78a local variable of the function, it is a volatile or it has an alias (pointer79or reference) then no warning is issued.80 81 82Limitations83-----------84 85The ``else`` branch is not checked currently for negated condition variable:86 87.. code-block:: c88 89  bool onFire = isBurning();90  if (onFire) {91    scream();92  } else {93    if (!onFire) {94      continueWork();95    }96  }97 98The checker currently only detects redundant checking of single condition99variables. More complex expressions are not checked:100 101.. code-block:: c102 103  if (peopleInTheBuilding == 1) {104    if (peopleInTheBuilding == 1) {105      doSomething();106    }107  }108