brintos

brintos / llvm-project-archived public Read only

0
0
Text · 1.8 KiB · efba0cc Raw
56 lines · plain
1.. title:: clang-tidy - bugprone-too-small-loop-variable2 3bugprone-too-small-loop-variable4================================5 6Detects those ``for`` loops that have a loop variable with a "too small" type7which means this type can't represent all values which are part of the8iteration range.9 10.. code-block:: c++11 12  int main() {13    long size = 294967296l;14    for (short i = 0; i < size; ++i) {}15  }16 17This ``for`` loop is an infinite loop because the ``short`` type can't18represent all values in the ``[0..size]`` interval.19 20In a real use case size means a container's size which depends on the21user input.22 23.. code-block:: c++24 25  int doSomething(const std::vector& items) {26    for (short i = 0; i < items.size(); ++i) {}27  }28 29This algorithm works for a small amount of objects, but will lead to freeze for30a larger user input.31 32It's recommended to enable the compiler warning33`-Wtautological-constant-out-of-range-compare` as well, since check does34not inspect compile-time constant loop boundaries to avoid overlaps with35the warning.36 37Options38-------39 40.. option:: MagnitudeBitsUpperLimit41 42  Upper limit for the magnitude bits of the loop variable. If it's set the check43  filters out those catches in which the loop variable's type has more magnitude44  bits as the specified upper limit. The default value is 16.45  For example, if the user sets this option to 31 (bits), then a 32-bit ``unsigned int``46  is ignored by the check, however a 32-bit ``int`` is not (A 32-bit ``signed int``47  has 31 magnitude bits).48 49.. code-block:: c++50 51  int main() {52    long size = 294967296l;53    for (unsigned i = 0; i < size; ++i) {} // no warning with MagnitudeBitsUpperLimit = 31 on a system where unsigned is 32-bit54    for (int i = 0; i < size; ++i) {} // warning with MagnitudeBitsUpperLimit = 31 on a system where int is 32-bit55  }56