Narrowing conversion from char to double

血红的双手。 提交于 2020-12-26 07:28:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!