c++ - Why doesn't clang warn about implicit conversion from double to int, but do it when from long to int? -


in following code:

#include <iostream> int main() {   const long l = 4294967296;   int = l;   return i; //just silence compiler } 

the compiler warns implicit conversion (using -wall , -std=c++14) following:

warning: implicit conversion 'const long' 'int' changes value 4294967296 0 [-wconstant-conversion] 

which ok. there no warning if conversion double int, in following code:

#include <iostream> int main() {   const double d = 4294967296.0;   int = d;   return i; //just silence compiler } 

why compiler reacts differently in these situations?

note 1: clang version 3.6.2-svn240577-1~exp1

note 2: i've tested many others versions of gcc, clang , icc compiler explorer (gcc.godbolt.org). tested versions of gcc (with exception of 5.x) , icc threw warning. no clang version did it.

the conversion double integer type changes value "by design" (think 3.141592654 converted int).

the conversion long int int instead may or work or may undefined behavior depending on platform , on value (the guarantee int not bigger long int, may same size).

in other words problems in conversions between integer types incidental artifacts of implementation, not by-design decisions. warning them better if can detected at compile time doesn't work because of limitations.

note conversion double int legal , defined (if done within boundaries) , implementation not required warn when loss of precision can seen @ compile time. compilers warn when use meaningful can problem (you disable warnings or worse habit of accepting non-clean build normal).

these implicit conversion rules may add other c++ wrinkles getting odd-looking , hard justify behaviors like:

std::string s; s = 3.141592654; // no warnings, no errors (last time checked) 

don't try use logic c++. reading specs works better.


Comments