缩小从 char 到 double 的转换
Narrowing conversion from char to double
为什么会有警告
narrowing conversion from char to double
我已经知道对于 const char 不会有警告。对此有很多答案。但我想知道,为什么对于非常量字符会有 "might-narrow" 警告?
是否有可能在某些系统上尾数不大而不能完美地表示字符?
int main() {
char c{7};
double a{c};
}
4:13: warning: narrowing conversion of 'c' from 'char' to 'double'
inside { } [-Wnarrowing]
它正在缩小,因为标准是这么说的。
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 [...]
列表初始化不允许缩小。使用显式转换 (cast)。
double a{static_cast<double>(c)};
是的,理论上允许 char
不完全表示为 double
,例如当两者都是 32 位类型时。这是人为设计的,但标准允许这样的实现。
为什么会有警告
narrowing conversion from char to double
我已经知道对于 const char 不会有警告。对此有很多答案。但我想知道,为什么对于非常量字符会有 "might-narrow" 警告?
是否有可能在某些系统上尾数不大而不能完美地表示字符?
int main() {
char c{7};
double a{c};
}
4:13: warning: narrowing conversion of 'c' from 'char' to 'double' inside { } [-Wnarrowing]
它正在缩小,因为标准是这么说的。
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 [...]
列表初始化不允许缩小。使用显式转换 (cast)。
double a{static_cast<double>(c)};
是的,理论上允许 char
不完全表示为 double
,例如当两者都是 32 位类型时。这是人为设计的,但标准允许这样的实现。