2

I wonder if someone can clarify what the "f" behind a floating point number is used to signify?

float myFloat = 12.0f;

as apposed to:

float myFloat = 12.0;

I have seen this used many times but its pretty hard to find an explanation either online or in books. I am assuming its either something carried over from another language thats supported for consistency by C or maybe its there as a directive for the compiler when it comes to evaluate the maths.

I am just curious if there is any practical difference between the "f" and using the "." to signify a floating point number?

fuzzygoat
  • 26,573
  • 48
  • 165
  • 294
  • Potential dupe. Could you clarify how your question might be different than this one: http://stackoverflow.com/questions/3696902/difference-between-2-0-and-2-0f – Wayne Hartman Feb 08 '11 at 13:52
  • 2
    The two questions do cover the same ground, if I had to give a difference I might be so bold as to suggest that this question is clearer and better worded, the answer and comments by @paxdiablo are likewise clear and succinct. – fuzzygoat Feb 08 '11 at 14:10

2 Answers2

5

It means it's a single-precision float rather than a double precision double.

From the C99 standard:

An unsuffixed floating constant has type double. If suffixed by the letter f or F, it has type float.

Objective-C is based on C, maybe not C99, but this convention has been around in C for a long time.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • ok, I already thought it was, I thought "double myFloat = 12.0;" was double precision. – fuzzygoat Feb 08 '11 at 13:46
  • No, the `12.0` itself is double. You may _assign_ it to a float (as you do in your question) but it may well lose precision in the process. – paxdiablo Feb 08 '11 at 13:48
  • I understand, the actually floating point constant 12.0 is taken to be of type double, which in turn is assigned to a float and may be truncated. Just curious as I have never used "f". – fuzzygoat Feb 08 '11 at 13:53
0

There are sometimes performance concerns when converting from float to double, and you can avoid them by using the 'f'. Also when doing say a square root, sin,cos, etc, a wild guess would say that

float answer = sqrt(12.0f)

is about 10x slower than

float answer = sqrtf(12.0f)

It really makes a difference on the phone and iPad, if you are doing millions of these kinds of operations. Stay in float if you need speed and can deal with the lower resolution. If you are not good at math, or not using much math in your program use double everywhere, as there are more gotchas when using the lower precision 32 bit float.

Tom Andersen
  • 7,132
  • 3
  • 38
  • 55