从char到double的转换变窄 [英] Narrowing conversion from char to double

查看:55
本文介绍了从char到double的转换变窄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么会有警告

缩小从char到double的转换

narrowing conversion from char to double

我已经知道对于const char不会有任何警告.关于这个有很多答案.但是我想知道,为什么对于非const char来说会出现警惕"的警告?

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?

在某些系统上尾数可能不大以完美表示char吗?

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:警告:缩小'c'从'char'到'double'的转换内{} [-缩小]

4:13: warning: narrowing conversion of 'c' from 'char' to 'double' inside { } [-Wnarrowing]

推荐答案

它正在缩小,因为标准如此规定.

It is narrowing because the standard says so.

7 缩小转换是隐式转换
[...]
(7.3)— 从整数类型或无作用域枚举类型到浮点类型,除非源是常量表达式,并且转换后的实际值将适合目标类型并产生转换回原始类型时的原始值[...]

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)};

是的,理论上允许 char 不能精确地表示为 double ,例如当两者都是32位类型时.这是人为的,但是标准允许这种实现.

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.

这篇关于从char到double的转换变窄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆