brintos

brintos / llvm-project-archived public Read only

0
0
Text · 2.6 KiB · f3f0331 Raw
69 lines · plain
1.. title:: clang-tidy - bugprone-inc-dec-in-conditions2 3bugprone-inc-dec-in-conditions4==============================5 6Detects when a variable is both incremented/decremented and referenced inside a7complex condition and suggests moving them outside to avoid ambiguity in the8variable's value.9 10When a variable is modified and also used in a complex condition, it can lead11to unexpected behavior. The side-effect of changing the variable's value within12the condition can make the code difficult to reason about. Additionally, the13developer's intended timing for the modification of the variable may not be14clear, leading to misunderstandings and errors. This can be particularly15problematic when the condition involves logical operators like ``&&`` and16``||``, where the order of evaluation can further complicate the situation.17 18Consider the following example:19 20.. code-block:: c++21 22  int i = 0;23  // ...24  if (i++ < 5 && i > 0) {25    // do something26  }27 28In this example, the result of the expression may not be what the developer29intended. The original intention of the developer could be to increment ``i``30after the entire condition is evaluated, but in reality, i will be incremented31before ``i > 0`` is executed. This can lead to unexpected behavior and bugs in32the code. To fix this issue, the developer should separate the increment33operation from the condition and perform it separately. For example, they can34increment ``i`` in a separate statement before or after the condition is35evaluated. This ensures that the value of ``i`` is predictable and consistent36throughout the code.37 38.. code-block:: c++39 40  int i = 0;41  // ...42  i++;43  if (i <= 5 && i > 0) {44    // do something45  }46 47Another common issue occurs when multiple increments or decrements are48performed on the same variable inside a complex condition. For example:49 50.. code-block:: c++51 52  int i = 4;53  // ...54  if (i++ < 5 || --i > 2) {55    // do something56  }57 58There is a potential issue with this code due to the order of evaluation in59C++. The ``||`` operator used in the condition statement guarantees that if60the first operand evaluates to ``true``, the second operand will not be61evaluated. This means that if ``i`` were initially ``4``, the first operand62``i < 5`` would evaluate to ``true`` and the second operand ``i > 2`` would63not be evaluated. As a result, the decrement operation ``--i`` would not be64executed and ``i`` would hold value ``5``, which may not be the intended65behavior for the developer.66 67To avoid this potential issue, the both increment and decrement operation on68``i`` should be moved outside the condition statement.69