CGFloat: round, floor, abs, and 32/64 bit precision

leecbaker picture leecbaker · Oct 8, 2011 · Viewed 8.3k times · Source

TLDR: How do I call standard floating point code in a way that compiles both 32 and 64 bit CGFloats without warnings?


CGFloat is defined as either double or float, depending on the compiler settings and platform. I'm trying to write code that works well in both situations, without generating a lot of warnings.

When I use functions like floor, abs, ceil, and other simple floating point operations, I get warnings about values being truncated. For example:

warning: implicit conversion shortens 64-bit value into a 32-bit value

I'm not concerned about correctness or loss of precision in of calculations, as I realize that I could just use the double precision versions of all functions all of the time (floor instead of floorf, etc); however, I would have to tolerate these errors.

Is there a way to write code cleanly that supports both 32 bit and 64 bit floats without having to either use a lot of #ifdef __ LP64 __ 's, or write wrapper functions for all of the standard floating point functions?

Answer

kennytm picture kennytm · Oct 8, 2011

You may use those functions from tgmath.h.

#include <tgmath.h>

...

double d = 1.5;
double e = floor(d);   // will choose the 64-bit version of 'floor'

float f = 1.5f;
float g = floor(f);    // will choose the 32-bit version of 'floorf'.