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

2

11

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?

Phira answered 8/10, 2011 at 5:8 Comment(0)
S
19

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'.
Sea answered 8/10, 2011 at 5:32 Comment(2)
Now that I know what to search for, I found this question: #5352957Phira
Note that in Xcode 6.1, including tgmath doesn't help if modules are enabled. See https://mcmap.net/q/131226/-tgmath-h-doesn-39-t-work-if-modules-are-enabled/449161Stadia
B
3

If you only need a few functions you can use this instead:

#if CGFLOAT_IS_DOUBLE
#define roundCGFloat(x) round(x)
#define floorCGFloat(x) floor(x)
#define ceilCGFloat(x) ceil(x)
#else
#define roundCGFloat(x) roundf(x)
#define floorCGFloat(x) floorf(x)
#define ceilCGFloat(x) ceilf(x)
#endif
Brettbretz answered 5/1, 2015 at 1:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.