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.
- Is this a likely cause of subtle errors?
- Is this only an issue for expressions or also for function parameters?
- Are there warning levels for GCC or Clang that warn about such implicit conversions?
- How about unsigned int, long int etc?
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:
changes to the following, truncating the result:
It’s a concern with function parameters as well when you have overloading and templates involved.
I know gcc has
-Wconversionbut I can’t recall everything that it covers.For integer values that fit in
intI usually don’t qualify those forlongorunsignedas there is usually much less chance there for subtle bugs.