Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a C++ float literal?

Tags:

c++

literals

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?

like image 650
Alan Clifford Avatar asked Jul 05 '18 10:07

Alan Clifford


1 Answers

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?

like image 121
Bathsheba Avatar answered Oct 24 '22 05:10

Bathsheba