tags:

views:

826

answers:

3

Just realized that I am getting errors on simple math if I mixed Integer with floats in iPhone SDK on the Simulator. Two examples:

float testVal1 = 10 + 5/10; 
//evaluates to 10 instead of 10.5 unless I use explicit 10.0f..

// Problem Code mixed float int 
NSUInteger jvalue = 2312345;

NSInteger testVal2 = (jvalue - 2512345); // evaluates correctly
float testVal3 = (jvalue - 2512345); // fails with some huge bogus value

I thought that in mixed mode expression it will convert to float values. Seems it is all or nothing while using floats, no mixing

What is going wrong here ?

+3  A: 

Nothing's going wrong; this is the way operations work. Take a look at your example:

float testVal1 = 10 + 5/10; //evaluates to 10

Here's the sequence of operations here:

  1. analyze 5: integer literal
  2. analyze 10: integer literal
  3. 5/10: integer division, result 0
  4. 10 + [0]: integer addition, result 10
  5. assign result to float

To make this work the way you want, at least one of the division operands must be floating-point. The result will now be more like this:

  1. analyze 5: integer literal
  2. analyze 10.0f: floating-point literal
  3. 5/10.0f: floating-point division, result 0.5
  4. 10 + [0.5]: floating-point addition, result 10.5
  5. assign result to float
John Feminella
10.0 instead of 10.0f should work too.
sigjuice
+2  A: 

This doesn't have anything to do with iPhone or the simulator, it has to do with how Objective-C and C perform arithmetic. The compiler interprets the operands to 5/10 as integers and integer division can't result in a fractional result, by definition. Thus, 10 + 5/10 == 10 + 0 == 10. You might try:

float testVal1 = 10.0f + 5.0f/10.0f;
drewh
+1  A: 

The default data type in a sub-expression like 5 / 10 is integer until one of the operands says otherwise. However (5 / 10) = 0 due to integer division.

In the expression NSInteger testVal2 = (jvalue - 2512345);, the default type of sub-expression is an unsigned integer; your negative result causes underflow and a bogus value.

dirkgently