views:

81

answers:

2

I've seen several examples in books and around the web where they sometimes use decimal places when declaring float values even if they are whole numbers, and sometimes using an "f" suffix. Is this necessary?

For example:

[UIColor colorWithRed:0.8 green:0.914 blue:0.9 alpha:1.00];

How is this different from:

[UIColor colorWithRed:0.8f green:0.914f blue:0.9f alpha:1.00f];

Does the trailing "f" mean anything special?

Getting rid of the trailing zeros for the alpha value works too, so it becomes:

[UIColor colorWithRed:0.8 green:0.914 blue:0.9 alpha:1];

So are the decimal zeros just there to remind myself and others that the value is a float?

Just one of those things that has puzzled me so any clarification is welcome :)

A: 

Trailing f: this is a float.

Trailing f + "." - redundant.

That simple.

8f is 8 as a float.

8.0 is 8 as a float.

8 is 8 as integer.

8.0f is 8 as a float.

Mostly the "f" can be style - to make sure it is a float, not a double.

TomTom
Thanks TomTom. So is there any reason why I should or shouldn't write alpha:1 instead of alpha:1f?
Paulo Fierro
Actually "1.0" is usually treated as a double, not a float.
John Cromartie
+5  A: 

Decimal literals are treated as double by default. Using 1.0f tells the compiler to use a float (which is smaller than double) instead. In most cases it doesn't really matter if a number is a double or a float, the compiler will make sure you get the right format for the job in the end. In high-performance code you may want to be explicit, but I'd suggest benchmarking it yourself.

John Cromartie
To follow on: the first-generation iPhone had no native double-precision support (it's handled in software emulation), so programmers have taken to adding the "f" to get a tiny boost in performance.
Brad Larson