Can anyone explain what is going on?
In C the type used by an operator is picked based on that operator's operands and not based on the type where you store the result.
Also everything including constants has a type. 8000
is type int
, 8000.0
is type double
and 8000.0f
is type float
.
In case of 1/Fs
with Fs
as a macro for the integer 8000
, then both operands of the division are int
. Therefore the division is carried out on int
type and you get the result 0
because of it.
In case of 1/Fs
with Fs
as type float
, one operand of the division is int
and the other is float
. Something called "the usual arithmetic conversions" (see Implicit type promotion rules) then "promotes" the int
to type float
. The division is carried out on float
type.
Some best practices:
- Avoid mixing integers/
int
constants with floating point arithmetic. Instead write every expression involving floating point with pure floating point constants/variables.
- Use
8000.0f
when dealing with float
and 8000.0
when dealing with double
.
float
is a type that should barely ever be used in C programs and never in beginner programs. The only scenario where you should ever use float
is when your CPU has a single precision FPU but no hardware support for double
precision - which is a very specific scenario and not applicable to modern x86 PC where double
should be used everywhere.
- Avoid writing code relying on implicit type promotions. If correct types are used from the start, such promotions can be avoided.