I've been trying to reduce implicit type conversions when I use named constants in my code. For example rather than using
const double foo = 5;
I would use
const double foo = 5.0;
so that a type conversion doesn't need to take place. However, in expressions where I do something like this...
const double halfFoo = foo / 2;
etc. Is that 2 evaluated as an integer and is it implicitly converted? Should I use a 2.0 instead?
The
2
is implicitly converted to a double becausefoo
is a double. You do have to be careful because iffoo
was, say, an integer, integer division would be performed and then the result would be stored inhalfFoo
.I think it is good practice to always use floating-point literals (e.g.
2.0
or2.
wherever you intend for them to be used as floating-point values. It's more consistent and can help you to find pernicious bugs that can crop up with this sort of thing.