I have a vector containing integer values, which I wish to sum. However, it’s summing the total wrong – if the vector holds 10 ints between -10 and 10, my total should not be 18446744073709551602.
I declare the vector, and populate it with values:
std::vector<int> X;
for ( int i = 0; i < readings.size() ; ++i ) {
X.push_back(readings[i].x);
I then sum and display:
unsigned long temptotal = 0;
for ( int i = 0; i < readings.size() ; ++i ) {
std::cout << "Value in X: " << X[i] << std::endl;
temptotal += X[i];
}
std::cout << "Temp total: " << temptotal << std::endl;
which produces the following output: Temp total: 18446744073709551603.
When I step through the summation loop in GDB, (at temptotal += X[i];), I can print X[i]:
(gdb) p X[i]
$1 = (reference) @0x100100c80: -1
Printing temptotal before and after the addition is performed:
(gdb) p temptotal
$2 = 0
(gdb) p temptotal
$3 = 18446744073709551615
I’m fairly sure that I’m adding the memory locations rather than the values in the memory locations – I could be wrong on that – but I’m not sure why I’m not adding the values at X[i]. When I populate X with the values from readings[i].x, they’re doubles, which I then type-cast to ints. Is this where my error is? Checking in GDB, my type-cast of the readings[i].x value should be an int, or, at least, a number of some kind:
(gdb) p (int)readings[i].x
$1 = -1
I’m stumped; if somebody could shed some light on why I’m not adding what I think I’m adding, I’d be grateful.
EDIT
It’s the casting from int to unsigned long. I went over it and over it, pressed “submit question” and spotted my error. Although, I still don’t understand why it’s doing what it’s doing – any light shed on that would be wonderful – why, if I’m adding an int to an unsigned long, does it not take the value from the int?
This is because your
temptotalis unsigned. All numbers added to it are interpreted as unsigned, hence small negative numbers become large positive numbers in two’s complement representation.