skip to content

Why does std::accumulate(v.begin(), v.end(), 0) return a wrong total for a C++ vector of doubles or 64-bit byte counts?

level: middleimportance: must knowfreq 55%

answer

  1. the third argument's type
  2. accumulator is T, not value_type
  3. every step converts back
  4. 0.0 or an explicit int64

basics

~20 s

std::accumulate's accumulator has the type of the init argument, not the element type. With 0 it is int, so each partial sum of doubles is truncated and 64-bit sums wrap. Pass 0.0, std::int64_t{0} or a value of the element type.

solid answer

~40 s

`std::accumulate(first, last, init)` is declared `template<class InputIterator, class T> T accumulate(..., T init)`: the template argument `T` is deduced from `init`, the accumulator is a `T`, and each step is `acc = std::move(acc) + *i` (the `std::move` since C++20), converting the result back to `T`. With the literal `0`, `T` is `int`. For `std::vector<double>{0.5, 0.5, 0.5, 0.5}` every partial sum `0 + 0.5` is truncated back to `0`, so the result is `0`, not `2`. For 64-bit byte counts, the sum is converted back to `int` after each step and wraps (well-defined as modular since C++20). No warning appears by default, because the conversion happens inside a system header. Pass an initial value of the type you want: `0.0`, `std::int64_t{0}`, or `decltype(v)::value_type{}`.

code

cpp · 16 lines
cpp
#include <cstdint>
#include <iostream>
#include <numeric>
#include <vector>

int main() {
    std::vector<double> sizesMiB{0.5, 0.5, 0.5, 0.5};
    std::vector<std::int64_t> bytes{3'000'000'000, 3'000'000'000};

    auto a = std::accumulate(sizesMiB.begin(), sizesMiB.end(), 0);    // T = int
    auto b = std::accumulate(sizesMiB.begin(), sizesMiB.end(), 0.0);  // T = double
    auto c = std::accumulate(bytes.begin(), bytes.end(), 0);          // T = int
    auto d = std::accumulate(bytes.begin(), bytes.end(), std::int64_t{0});

    std::cout << a << ' ' << b << '\n' << c << ' ' << d << '\n';
}

go deeper

for a junior

Remember that the third argument of std::accumulate sets the result type, so pass 0.0 for doubles.

for a middle

Explain T deduction from init, the per-step conversion back to T, and why no warning appears from inside the standard header.

for a senior

Review numeric code for accumulators narrower than their data, including float sums that drift, and pick a wider accumulator deliberately.

for a principal

Decide where numeric precision is a requirement and enforce it with typed helpers or static analysis rather than case-by-case review.

## The declaration decides the type `std::accumulate` lives in `<numeric>`: ```cpp template<class InputIterator, class T> constexpr T accumulate(InputIterator first, InputIterator last, T init); ``` `T` is deduced **from `init` alone**. The standard specifies the algorithm as: initialise an accumulator `acc` of type `T` with `init`, then for each element in order perform `acc = std::move(acc) + *i`, and return `acc`. The element type matters only inside the addition; the result of every step is assigned back into a `T`. ## What the literal 0 does The literal `0` has type `int`, so `T` is `int`: | Elements | Call | Result | Why | |---|---|---|---| | `double` 0.5 x 4 | `accumulate(..., 0)` | `0` | `0 + 0.5` is `0.5`, assigned to `int` truncates to `0`, every time | | `double` 0.5 x 4 | `accumulate(..., 0.0)` | `2` | accumulator is `double` | | `int64_t` 3,000,000,000 x 2 | `accumulate(..., 0)` | `1705032704` | each sum is converted back to 32-bit `int` and wraps | | `int64_t` 3,000,000,000 x 2 | `accumulate(..., std::int64_t{0})` | `6000000000` | accumulator is 64-bit | The truncation happens on **every step**, not only at the end, which is why a vector of values below 1.0 can sum to exactly zero. For integers, converting an out-of-range value to a signed type has been defined as modular since C++20; before C++20 it was implementation-defined. Either way the answer is wrong, and no undefined-behaviour sanitizer will flag it. ## Why the compiler stays quiet The narrowing assignment sits inside the standard library's own template, and compilers suppress most warnings in system headers. Built with `-Wall -Wextra -Wconversion` on Apple clang 21, the example below compiles without a single warning. A code review, a test with fractional data, or a clang-tidy check on the call site is what catches it. ## Getting it right - **Match the element type:** `std::accumulate(v.begin(), v.end(), 0.0)` for doubles; `std::accumulate(v.begin(), v.end(), std::int64_t{0})` for 64-bit counts. - **Write it generically:** `std::accumulate(v.begin(), v.end(), typename Container::value_type{})` in templates. - **Widen on purpose:** summing `float` latencies into a `double` (`0.0`) gives a more accurate total than a `float` accumulator, because rounding error accumulates over millions of additions. - **Use `std::reduce` without an init** if you want the element type automatically: its two-argument form uses `value_type{}` as the initial value - but `reduce` has different ordering rules, covered with `reduce` itself. ## Beyond plus The four-argument form takes any binary operation: `std::accumulate(first, last, init, op)` computes `acc = op(std::move(acc), *i)`. It is a strict left fold, so it works for non-commutative operations such as building a string. Since C++20 the accumulator is moved into each call, so concatenating strings with `std::accumulate(words.begin(), words.end(), std::string{})` no longer copies the growing string on every step. The same init-type rule applies: with a `const char*` initial value such as `""`, `T` is `const char*`, and `const char* + std::string` yields a `std::string` that cannot be assigned back - a compile error rather than a silent bug. ## A checklist for reviewing reductions When a pull request adds a sum, a count or an average, four quick checks catch nearly every variant of this bug: 1. **What is the type of the third argument?** A bare `0` is an `int`, `0u` an `unsigned int`, `0.0f` a `float`. Each sets the width of the whole computation. 2. **Can the total exceed that type?** Byte counts across a day of logs exceed 2^31 easily; frame counts and timestamps in milliseconds do too. 3. **Is the data fractional?** Any `float` or `double` element with an integer accumulator is a truncation. 4. **Is precision part of the requirement?** A billing total and a dashboard estimate deserve different accumulators. Writing the type out - `std::int64_t{0}`, `0.0`, `Money{}` - makes the decision visible in review instead of leaving it to template argument deduction. ## In an interview Name the rule (the return and accumulator type come from `init`), show the truncation with a tiny example, give the fix, and mention that the conversion is silent because it happens in library code. That is the full middle-level answer.

  • Why does std::accumulate(words.begin(), words.end(), "") fail to compile for a vector of std::string?
    `T` is deduced from `""` as `const char*`. The first step evaluates `const char* + std::string`, which produces a `std::string`, and that cannot be assigned back into a `const char*` accumulator. Passing `std::string{}` as the initial value makes the accumulator a `std::string` and the fold works.
  • Should you sum a million float latencies with a float or a double accumulator?
    Use a double: `std::accumulate(v.begin(), v.end(), 0.0)`. With a float accumulator, once the running total is large each small addend loses most of its significant bits, and the error grows with the count; a test summing ten million values in [0, 5) drifted by over one percent. The double accumulator keeps the error far smaller at negligible cost.

  • Saying accumulate's result type is the element type
  • Believing the truncation happens only once at the end
  • Expecting a compiler warning for accumulate(..., 0) on doubles
  • Writing "" as the initial value for a string fold
  • Calling the wrapped 64-bit sum undefined behaviour in C++20

Assumes C++23; accumulate moves the accumulator into each step since C++20, and out-of-range conversion to a signed integer is modular since C++20 (implementation-defined before).