0

I've got an NSDictionary made up of titles and floats (although they're stored as strings, for what it's worth), along the lines of "Paid for Dinner":"15.00". Right now, those entries are (15, 25.25, 25.75, 15), which should add up to 81. (And I've checked in the debugger, those are the correct values being stored, so it isn't a data source problem.)

I want to get the sum of all the entries programmatically, so I've got a fairly simple bit of code to do that:

float currentTotal;
for(id key in thisSet) {
    currentTotal = currentTotal + [[thisSet objectForKey:key] floatValue];
}

By the end of the function, currentTotal is correctly set at 81.

Thing is, when I leave that ViewController and then return back to it, (by going from the MasterView, where I was, to the DetailView and then back, if it matters), the same function with the same values will return 81.006.

The values didn't change (I checked the debugger again, it's still precisely (15, 25.25, 25.75, 15)) and the code didn't change, so why would simply moving from to another View and back change the result?

NOTE: I know about floating point addition errors and such from other answers like this and this. I'm not looking for why floating point operations can be imprecise, I'm wondering why a change in View would affect the results.

Community
  • 1
  • 1
Nerrolken
  • 1,975
  • 3
  • 24
  • 53
  • PS I changed all the "float" references to "double" and it fixed the problem, but I'd still love to know why the same function would return one thing on launch, then change to a different thing upon returning to the same ViewController and stay with the second result from then on? – Nerrolken Jun 28 '13 at 22:42
  • 1
    In your code `currentTotal` is not initialized to zero. Is that actually missing or did you just not show it? Could that be the reason for different results? – Martin R Jun 28 '13 at 22:45
  • That was actually missing, but either way it should be the same every time it executes, right? Whatever it does the first time should be the same thing it does the second time, it seems like. So why would it change upon returning to the View? – Nerrolken Jun 28 '13 at 22:51
  • 1
    When a variable is deallocated the memory isn't cleaned, so if you push a variable into the stack and you don't assign it, you get old values. But you can't know what was on the stack before calling the function, so it's undefined behavior. – Ramy Al Zuhouri Jun 28 '13 at 23:01

1 Answers1

1

The local variable currentTotal must be assigned a value (zero in your case) before it is used, otherwise its contents is undefined and may be different on each invocation of the function.

(The Static Analyzer should warn you about this.)

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382