static_assert(sizeof(unsigned) == 4, ":(");
static_assert(sizeof(double) == 8 ,":(");
unsigned u{42};
double x{u};
g++ 4.7.1 complains about this code:
warning: narrowing conversion of 'u' from 'unsigned int' to 'double' inside { }
Why is this a narrowing conversion? Isn't every unsigned
perfectly representable as a double
?
(Let's try:)
double
has exactly 52 bits of significant (binary) digits (according to ieee standard), whereasunsigned int
may have good 64 bits on some other system. So the actualunsigned int
's width on your system may be of no value for this check.Because the definition includes (with my emphasis):
u
is not a constant expression, so it's a narrowing conversion whether or not all possible values of the source type might be representable in the target type.That's implementation defined. In the common case of 32-bit
unsigned
anddouble
with a 52-bit mantissa, that is the case; but some implementations have largerunsigned
and/or smallerdouble
representations, so code that depends on that assumption is not portable.The warning you have because you initialize x with non-constant expression
As you can see the code above works without any warning or errors