What is the difference between casting to `float` and adding `f` as a suffix when initializing a `float`?
float f = 99.32f ;
That is a float
literal, which means a float variable being assigned with a float
value directly.
float f = (float) 99.32 ;
That is a float
variable that is assigned a double
value that is cast to float
before being assigned.
The difference may be optimized away, but in the first case you have a double literal that is type casted to a float while you have a float literal in the second case.
If not optimized away you will get a typecast in the code in the second example.
However there are corner cases where the result could (depending on rounding mode) be slightly different. If your number can't be exactly represented you will in the first case get rounding twice - first when you round the decimal representation to a double and then when you round that to a float, while in the first case you round the decimal representation directly to a float.
In the first case without the cast 99.32
is interpreted as double not as a float.
A double literal is being casted to float.
In the second case you have a suffix f
to make sure the compiler treats 99.32
as float.