简体   繁体   中英

Narrowing conversion from char to double

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]

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 , eg when both are 32-bit types. This is contrived but the standard allows for such an implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM