xref: /llvm-project/clang-tools-extra/docs/clang-tidy/checks/bugprone/fold-init-type.rst (revision 6e566bc5523f743bc34a7e26f050f1f2b4d699a8)
1.. title:: clang-tidy - bugprone-fold-init-type
2
3bugprone-fold-init-type
4=======================
5
6The check flags type mismatches in
7`folds <https://en.wikipedia.org/wiki/Fold_(higher-order_function)>`_
8like ``std::accumulate`` that might result in loss of precision.
9``std::accumulate`` folds an input range into an initial value using the type of
10the latter, with ``operator+`` by default. This can cause loss of precision
11through:
12
13- Truncation: The following code uses a floating point range and an int
14  initial value, so truncation will happen at every application of ``operator+``
15  and the result will be `0`, which might not be what the user expected.
16
17.. code-block:: c++
18
19  auto a = {0.5f, 0.5f, 0.5f, 0.5f};
20  return std::accumulate(std::begin(a), std::end(a), 0);
21
22- Overflow: The following code also returns `0`.
23
24.. code-block:: c++
25
26  auto a = {65536LL * 65536 * 65536};
27  return std::accumulate(std::begin(a), std::end(a), 0);
28