1.. title:: clang-tidy - bugprone-too-small-loop-variable 2 3bugprone-too-small-loop-variable 4================================ 5 6Detects those ``for`` loops that have a loop variable with a "too small" type 7which means this type can't represent all values which are part of the 8iteration 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't represent 18all values in the ``[0..size]`` interval. 19 20In a real use case size means a container's size which depends on the user input. 21 22.. code-block:: c++ 23 24 int doSomething(const std::vector& items) { 25 for (short i = 0; i < items.size(); ++i) {} 26 } 27 28This algorithm works for a small amount of objects, but will lead to freeze for 29a larger user input. 30 31It's recommended to enable the compiler warning 32`-Wtautological-constant-out-of-range-compare` as well, since check does not 33inspect compile-time constant loop boundaries to avoid overlaps with the warning. 34 35.. option:: MagnitudeBitsUpperLimit 36 37 Upper limit for the magnitude bits of the loop variable. If it's set the check 38 filters out those catches in which the loop variable's type has more magnitude 39 bits as the specified upper limit. The default value is 16. 40 For example, if the user sets this option to 31 (bits), then a 32-bit ``unsigned int`` 41 is ignored by the check, however a 32-bit ``int`` is not (A 32-bit ``signed int`` 42 has 31 magnitude bits). 43 44.. code-block:: c++ 45 46 int main() { 47 long size = 294967296l; 48 for (unsigned i = 0; i < size; ++i) {} // no warning with MagnitudeBitsUpperLimit = 31 on a system where unsigned is 32-bit 49 for (int i = 0; i < size; ++i) {} // warning with MagnitudeBitsUpperLimit = 31 on a system where int is 32-bit 50 } 51