2

Can someone explain why this causes the error stated in the title?

CGFloat dx = fabs(lastPoint.x - currentPoint.x);

Thanks

Venk
  • 5,949
  • 9
  • 41
  • 52
user7865437
  • 812
  • 14
  • 28

2 Answers2

3

fabs() returns a double (64-bit), but CGFloat is defined to be a float (32-bit). It's generally harmless – I personally would even disable the compiler warning, as performing calculations using double values is typically at least as fast as using float values.

Justin Spahr-Summers
  • 16,893
  • 2
  • 61
  • 79
  • "performing calculations using double values is typically at least as fast as using float values." are you sure about that on the ARM? – Rog Dec 09 '10 at 15:42
  • 1
    ARM has characteristics similar to PowerPC in that regard. As far as I know, both processors have to explicitly "shorten" floating-point values after performing calculations in order to pare them back down into floats before storing them in registers. The performance characteristics may not be the same in thumb code, though, where space is perhaps more important. – Justin Spahr-Summers Dec 09 '10 at 17:59
  • Aha, thanks! I decided to cast to CGFloat which looks ugly in code. Have never disabled a compiler warning tho? – user7865437 Dec 09 '10 at 18:21
  • 1
    @user7865437 If you don't like either of those solutions, floating-point functions are usually provided with `float` return values too. In this case, it'd be `fabsf()`. – Justin Spahr-Summers Dec 09 '10 at 19:01
  • So you mean use float rather than CGFloat? – user7865437 Dec 09 '10 at 21:15
  • No, I was referring to the fact that `float` and `CGFloat` are identical under the hood, so using a function that returns a `float` would eliminate that warning. – Justin Spahr-Summers Dec 09 '10 at 22:11
  • I'd like to update this answer: now `CGFloat` can be either `float` or `double` - basing on architecture (32/64bit). – Nat Feb 17 '15 at 08:45
2

A better answer is to use #include <tgmath.h>. That header defines "adaptive" functions that call the correct function on whichever parameter size.

With that header included, you can simply call fabs without getting that warning (nor worrying about loss of precision caused by the use of the wrong function).

Jean-Denis Muys
  • 6,772
  • 7
  • 45
  • 71