C/C++ implicit conversions can cause bugs. Here's one example:
int foo, bar; scanf("%d", &foo); scanf("%d", &bar); float foobar = foo / bar;
If I input
2, it's not
3.5 as expected - it's
3 -> bug (let's ignore the buffer overflow).
-Wconversion warns about this kind of stuff, so I turned it on. But it just seems to me like it's going over the top with the warnings. For instance, this:
int foo; float bar; scanf("%d", &foo); scanf("%f", &bar); float foobar = foo / bar;
Causes a warning:
warning: conversion to 'float' from 'int' may alter its value [-Wconversion]
Even though it works as intended, returning
3.5 when I input
2. I know that float cannot represent all possible int values precisely, but I'm questioning if adding a cast here does anything to help - other than adding more code. In the example above, casting one of the int values in the expression to float actually changed the result, replacing an implicit cast by an explicit one in this example doesn't.
So much for float to int conversion warnings, but that's not all. There's also sign conversion warnings. Traditional example:
std::vector<char> chars = get_chars(); for (int i = 0; i < chars.size(); i++) std::cout << chars[i] << std::endl;
Causes this warning:
warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
I could use the more cumbersome
unsigned int for the index variable instead - which will require further casting when I do calculations with it. All for the unusual situation that I have between
2^31 + 1 and
2^32 elements in my vector and don't do any calculations with the index variable that cast it to int.
So, my question is: Which conversion warnings make sense in practice? Does adding explicit casts to fix them really improve anything?