futlib
futlib

Reputation: 8408

Should I always use the appropriate literals for number types?

I'm often using the wrong literals in expressions, e.g. dividing a float by an int, like this:

float f = read_f();
float g = f / 2;

I believe that the compiler will in this case first convert the int literal (2) to float, and then apply the division operator. GCC and Clang have always let stuff like that pass, but Visual C++ warns about an implicit conversion. So I have to write it like this:

float f = read_f();
float g = f / 2.0f;

That got me wondering: Should I always use the appropriate literals for float, double, long etc.? I normally use int literals whenever I can get away with it, but I'm not sure if that's actually a good idea.

Upvotes: 3

Views: 360

Answers (2)

jthill
jthill

Reputation: 60275

There's pretty much never an absolutely correct answer to a "should" question. Who's going to use this code, and for what? That's relevant here. But also, particularly for anything to do with floats, it's good to get into the habit of specifying exactly the operations you require. float*float is done in single-precision. anything with a double is done double-precision, 2 gets converted to a double so you're specifying different operations here.

The best answer here is What Every Computer Scientist Should Know About Floating-Point Arithmetic. I'd say don't tl;dr it, there are no simple answers with floating point.

Upvotes: 1

Mark B
Mark B

Reputation: 96241

You should always explicitly indicate the type of literal that you intend to use. This will prevent problems when for example this sort of code:

float foo = 9.0f;
float bar = foo / 2;

changes to the following, truncating the result:

int foo = 9;
float bar = foo / 2;

It's a concern with function parameters as well when you have overloading and templates involved.

I know gcc has -Wconversion but I can't recall everything that it covers.

For integer values that fit in int I usually don't qualify those for long or unsigned as there is usually much less chance there for subtle bugs.

Upvotes: 2

Related Questions