问题
Why there is a warning
narrowing conversion from char to double
I know already that for const char there will be no warning. There are a lot of answers about that. But I would like to know, why for non-const char there is a "might-narrow" warning?
Is it possible that on some systems mantissa is not big to perfectly represent char?
int main() {
char c{7};
double a{c};
}
4:13: warning: narrowing conversion of 'c' from 'char' to 'double' inside { } [-Wnarrowing]
回答1:
It is narrowing because the standard says so.
7 A narrowing conversion is an implicit conversion
[...]
(7.3) — from an integer type or unscoped enumeration type to a floating-point type, except where the source is a constant expression and the actual value after conversion will fit into the target type and will produce the original value when converted back to the original type [...]
Narrowing is not allowed in list-initialization. Use an explicit conversion (cast).
double a{static_cast<double>(c)};
Yes, theoretically it is allowed for char
to be not exactly representable as double
, e.g. when both are 32-bit types. This is contrived but the standard allows for such an implementation.
来源:https://stackoverflow.com/questions/57491990/narrowing-conversion-from-char-to-double