Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't clang or gcc flag this implicit conversion from double to int?

Consider the following code:

void f(int x)
{
    std::cout << x << std::endl;
}

int main()
{
    double x = 1.5;
    f(x);
    return 0;
}

This compiles and runs without any warnings (using -Wall), and therefore hides a dangerous implicit cast from double to int. The compiler will catch the cast if the function is called with a literal, i.e.

f(1.5)

but this isn't all that useful. Why don't these compilers give warnings for this cast? I'm on OSX 10.8.3 with gcc-4.2.1 and clang-425.0.28.

like image 753
giogadi Avatar asked May 22 '13 19:05

giogadi


1 Answers

For posterity:

In order to avoid implicit conversions, use the -Wconversion flag (it's not included in -Wall). Clang actually includes -Wconversion in the -Weverything flag, but this flag enables quite a bit more warnings than most users are accustomed to.

like image 54
giogadi Avatar answered Sep 27 '22 21:09

giogadi