There are many places that I saw an author uses:
sprite.anchorPoint = CGPointMake(1, 0.5f);
that is, why not use 0.5
instead of 0.5f
-- is there advantage of using 0.5f
?
In c a value of 1 is an integer and 1.0 is a double, you use f after a decimal number to indicate that the compiler should treat it as a single precision floating point number.
The "F" indicates that the literal numeric value it is appended to is a float value. This is necessary information for the compiler and if not present can lead to errors or the compiler otherwise interpreting the number incorrectly.
'f' indicates that you want a float : 0 is an int. 0f is a float. 0.0 is a double.
It tells the computer that this is a floating point number (I assume you are talking about c/c++ here). If there is no f after the number, it is considered a double or an integer (depending on if there is a decimal or not).
0.5
is a double
constant, while 0.5f
is a float
constant.
is there advantage of using 0.5f?
yes. you either want to specify the type (read: precision) for the calculation or avoid implicit narrowing (and associated compiler warnings).
the example you provide isn't compelling, beyond avoiding compiler warnings or just being very exacting regarding the parameter type.
however, less-than-obvious promotions to double precision can be costly.
To answer "Should we use 0.5f or 0.5": Because there are appropriate times for each, you should be using both in your programs. You should either be using the type appropriate for the calculation/precision you need, the type for the parameter you pass, or the type appropriate for other values in the expression. This is just like integers -- there are appropriate times to consider widths, and there appropriate times to suffix (e.g. U
and L
). There are times when the distinction is important, and (naturally) times when it is not important.
The constant 0.5 declares a double in Objective-C, putting an f on the end - 0.5f declares the constant as a (32-bit) float.
Take a look at "f" after number/float in Objective-C/C post.
The trailing f
forces the constant to be a single-precision float
, as floating-point constants default to being double
s. This was more important a few compiler revisions ago, as I do not believe there was automatic type conversion for doubles to floats, as the compiler could not ensure that there were no side-effects to doing so. The result ended up being that a lot of code kept the f
specifier to avoid burning cycles on loading double-precision floating-point registers when only single-precision ones were needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With