A warning about conversion warnings in C++

/ 2019-09-05 14:24

C++ is really fun to work with, but it does make it really easy sometimes to shoot yourself in the foot.

Consider this program:

#include <iostream>

int main() {
    int foo = 1.5;
    std::cout << foo << "\n";
    return 0;
}

Obviously this outputs 1, not 1.5, and with clang++ by default you get a warning like this:

test.cpp:4:12: warning: implicit conversion from 'double' to 'int' changes value from 1.5 to 1 [-Wliteral-conversion]
        int foo = 1.5;
            ~~~   ^~~

So far, this makes total sense.

Let’s now modify this program slightly:

 #include <iostream>

 int main() {
-    int foo = 1.5;
+    int foo = 3 * 1.5;
     std::cout << foo << "\n";
     return 0;
 }

This outputs 4, but you don’t get any warning anymore! Only when enabling -Wconversion you get this:

test.cpp:4:14: warning: implicit conversion turns floating-point number into integer: 'double' to 'int' [-Wfloat-conversion]
        int foo = 3 * 1.5;
            ~~~   ~~^~~~~

Still makes sense to disable this warning by default, I think, because there is likely a lot of legacy code depending on these implicit conversions. However, this warning is not included in -Wall or -Wextra in both clang and g++! So I was hit by this and spent time debugging, even though I already had turned warnings up as much as possible.

From now on, -Wconversion is always going into my build flags.