Replacement for `fabs`, `fmax`, etc. for use with CGFloat on 64-bit iOS devices

元气小坏坏 提交于 2019-12-09 14:55:06

问题


Question

Consider layout code like this:

CGFloat descriptionHeight = // height of a paragraph of text with zero or more words;
CGFloat imageHeight = // height of an image;
CGFloat yCoordinateOfSomeOtherView = fmax(descriptionHeight, imageHeight) + 5.0f;

How should the third line be rewritten with support for 64-bit iOS devices?

(The current code doesn't take into account whether yCoordinateOfSomeOtherView is a float or a double.)

Options

A few options (I'm not sure which is best):

1. Define my own macro

#if defined(__LP64__) && __LP64__
#define cgfmax(x,y) fmaxf(x,y)
#else
#define cgfmax(x,y) fmax(x,y)
#endif

I could then replace fmax with cgfmax.

2. Use tgmath.h

This Stack Overflow answer from 2011 suggests replacing math.h with tgmath.h. This replaces the implementation of fmax with one that calls __typeof__ on each argument and returns either fmax or fmaxf depending on the argument types.

3. Ignore this issue

Since CGFloats relate to layout, the data loss potentially incurred storing a float into a double will usually be insignificant. That is, they'll represent tiny fractions of pixels.

Summary

I'm looking for any other options or helpful advice from someone who's done a 32-bit to 64-bit transition before.


回答1:


There is never any "data loss" incurred when converting a float into a double. That conversion is always exact.

Your solutions 1 & 2 are entirely equivalent semantically, though (2) is more stylistically correct.

Your solution 3 is formally not equivalent; it may incur extra conversions between float and double, which may make it slightly less efficient (but the actual result is identical).

Basically, it doesn't matter, but use tgmath.



来源:https://stackoverflow.com/questions/19506238/replacement-for-fabs-fmax-etc-for-use-with-cgfloat-on-64-bit-ios-devices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!