Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning for overflow in std::accumulate

Is there any way to get a warning for std::accumulate when the type of the init arg doesn't match the contained type you are accumulating over? e.g. in this example we shouldn't accumulate a 32 bit value when iterating over a vector of 64 bit ints. But it's pretty easy to just pass in 0 and forget to pass 0LL. Is there any way to get a warning for this? -Wall -Wextra -Wconversion doesn't seem to help. I also tried looking for clang tidy checks that may work, but didn't find anything there either.

std::vector<long long> a = {10000000000, 10000000000};
cout << std::accumulate(a.begin(), a.end(), 0) << "\n"; // overflows
cout << std::accumulate(a.begin(), a.end(), 0LL) << "\n"; // prints 20000000000
like image 364
Rick Buczynski Avatar asked Dec 21 '21 18:12

Rick Buczynski


1 Answers

Oh, I found the right clang-tidy check: misc-fold-init-type

like image 199
Rick Buczynski Avatar answered Oct 17 '22 08:10

Rick Buczynski