11

result is float and I could code this three ways:

  • if (result < 0)
  • if (result < 0.)
  • if (result < 0.f)

As I understand it,

  • 0 is implicitly int,
  • 0. is implicitly double
  • and 0.f is float.

I'd prefer to use the first method since it is clear and simple but am I forcing a type conversion by using it?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Alan Clifford
  • 141
  • 1
  • 5
  • 3
    The compiler already knows that you need 0.f, the conversion is applied at compile-time. So favor the syntax that is most readable. – Hans Passant Jul 05 '18 at 10:28
  • The compiler in general can optimise better than you or me. – n. m. could be an AI Jul 05 '18 at 10:34
  • 1
    Personally, I prefer `if (result < 0.f)` because when I see `if (result < 0)` I tend to think that `result` is integral. – Olivier Sohn Jul 05 '18 at 21:27
  • #2 looks like a typo, dont like it at all – pm100 Jul 05 '18 at 21:28
  • 1
    My personal preference is `if (result < 0.0)`. Using `0.0` tells the user that the value is floating-point. The fact that it's `double` rather than `float` is less important, and any implicit conversion is exact. (And, depending on the context, it's entirely possible that `result` should have been `double` rather than `float` in the first place.) You can have a `.` a the end of a floating-point constant, but I found `0.0` significantly more readable than `0.`. – Keith Thompson Jul 05 '18 at 22:01
  • Somewhat OT: Be careful when using comparison operators on floating-point numbers. Due to rounding errors, the results may be surprising. E.g. `float f=0.0f; for(int i=0; i<100; ++i) f+=0.01f;` – the result will not be equal to `1.0f` on an IEEE platform. (For this reason, I prefer to be explicit in writing `0.0f` in such a situation so that it's obvious that the comparison makes an assumption about floating-point behavior.) – Arne Vogel Jul 16 '18 at 08:17

1 Answers1

8

Conceptually yes, conversions are made.

But you should defer such micro-considerations to the compiler and write what's clearest which, for me is

if (result < 0)

If you are ever in any doubt, check the generated assembly (very easy with https://gcc.godbolt.org/).

Finally, when deciding to use a float over a double, consider double or float, which is faster?

Bathsheba
  • 231,907
  • 34
  • 361
  • 483