# <Functional>: plus<long>() on integers gives unexpected result

I don’t understand why I do not get the same results in these two cases:

#include <iostream> #include <vector> #include <numeric> // for accumulate #include <functional> // for plus() using namespace std; int main() { long long i = (long long) 0xFFFFFFFF + 2; cout << i << endl; vector<int> v; v.push_back(0xFFFFFFFF); v.push_back(2); long long r = accumulate(v.begin(), v.end(), 0, plus<long long>()); cout << r << endl; return 0; }

Anyone any ideas?

**EDIT:** as correctly pointed out below, this is due to the sign bit in int I wasn't counting on. 0x7FFFFFFF would obviously be better for testing. Also, I erroneously expected that the return type of plus() would be the same as for accumulate(), which is not the case: it is based on the third argument.

## Answers

There are two problems here:

The number 0xFFFFFFFF won't fit in an int (assuming 32-bit ints), so the value stored in the vector is actually -1 on most implementations. Using vector<unsigned int> or vector<long long> should fix this.

The type returned by accumulate is the type deduced from the third parameter. Since you passed in 0, this will be int. You should pass in 0LL instead so that it returns long long.

This program with both fixes will return the correct result:

#include <iostream> #include <vector> #include <numeric> // for accumulate #include <functional> // for plus() using namespace std; int main() { long long i = (long long) 0xFFFFFFFF + 2; cout << i << endl; vector<long long> v; //or vector<unsigned int> v.push_back(0xFFFFFFFF); v.push_back(2); long long r = accumulate(v.begin(), v.end(), 0LL, plus<long long>()); cout << r << endl; return 0; }