5

Should I be writing CGFloat values with postfix f or not?

CGFloat fValue = 1.2;

vs.

CGFloat fValue = 1.2f;

I know that this postfix define a float value. But is it necessary, does it make sense, are there any performance differences between using those two or is this just visual presentation so you can quickly define value type (e.g. float in this case)?

Borut Tomazin
  • 8,041
  • 11
  • 78
  • 91
  • 1
    http://stackoverflow.com/questions/2391818/f-after-number-float-in-objective-c-c – iphonic Mar 14 '13 at 09:14
  • 1
    http://stackoverflow.com/questions/14302898/is-it-better-to-write-0-0-0-0f-or-0f-instead-of-simple-0-for-supposed-float-or/14302912#14302912 – Anoop Vaidya Mar 20 '13 at 04:45

2 Answers2

6

1.2 is a double; i.e. 64-bit double-precision floating point number.

1.2f is a float; i.e. 32-bit single-precision floating point number.

In terms of performance, it doesn't matter as the compiler will convert literals from float to double and double to float as necessary. When assigning floating-point numbers from functions, however, you will most likely need to cast to avoid a compiler warning.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • It also doesn't matter because I doubt it is causing any measurable performance hits even if it were not being converted by the compiler. Judging by the wording, it screams premature optimization. – borrrden Mar 14 '13 at 09:17
  • Therefore should use postfix if I am operating with float values and omit it if using double. After all compiler has some extra work to do if I omit postfix for float values. But nowadays it should be no difference regarding performance. – Borut Tomazin Mar 14 '13 at 09:26
  • 1
    @BorutTomazin I wouldn't worry about it at all; I've seen many examples where literal integers are provided and this also works fine. Given the amount of work the compiler does to generate your object file, this is a *drop in the ocean*. – trojanfoe Mar 14 '13 at 09:28
0

The basic difference is as :

1.0 or 1. is a double constant

1.0f is a float constant

Without a suffix, a literal with a decimal in it (123.0) will be treated as a double-precision floating-point number.

If you assign or pass that to a single-precision variable or parameter, the compiler will (should) issue a warning. Appending f tells the compiler you want the literal to be treated as a single-precision floating-point number.

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140