Search code examples
c++performanceimplicit-typing

Implicit type conversions in expressions int to double


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?


Solution

  • The 2 is implicitly converted to a double because foo is a double. You do have to be careful because if foo was, say, an integer, integer division would be performed and then the result would be stored in halfFoo.

    I think it is good practice to always use floating-point literals (e.g. 2.0 or 2. 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.