In the following code:
#include <iostream>
int main()
{
const long l = 4294967296;
int i = l;
return i; //just to silence the compiler
}
the compiler warns about implicit conversion (using -Wall and -std=c++14) as following:
warning: implicit conversion from 'const long' to 'int' changes value from 4294967296 to 0 [-Wconstant-conversion]
which is ok. But there is no warning if the conversion is from double to int, as in the following code:
#include <iostream>
int main()
{
const double d = 4294967296.0;
int i = d;
return i; //just to silence the compiler
}
Why the compiler reacts differently in these situations?
Note 1: clang version is 3.6.2-svn240577-1~exp1
Note 2: I've tested it with many others versions of gcc, clang and icc thanks to Compiler Explorer (gcc.godbolt.org). So all tested versions of gcc (with exception of 5.x) and icc threw the warning. No clang version did it.
int
, the value4294967296.0
(exactly 2**32) is well outside the range ofint
. The conversion has undefined behavior. (I get4196368
and no warning with clang++,2147483647
and a warning with g++.) I'd say it's a bug in clang++. – Keith Thompson-Wconversion
, but the warning occurs even for non-problematic values, for exampleconst double d = 1.0; int i = d;
– Keith Thompsonlong
anddouble
variables. If the conversion fromlong
toint
loses information, then so does the conversion fromdouble
toint
. It is, after all, the same value. – IInspectable