为什么编译器允许缩小转换范围 [英] Why compiler allows narrowing conversions

查看:56
本文介绍了为什么编译器允许缩小转换范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以向我解释一下,如果初始化程序可能导致信息丢失,为什么编译器允许使用内置类型的初始化变量?

Can anyone please explain to me, why the compiler allows initialize variables of built-in type if the initializer might lead to the loss of information?

例如C ++第5版Primer说,如果初始化程序可能导致信息丢失,则编译器不会让我们列出内置类型的初始化变量。

For example C++ Primer, the 5th edition says, that The compiler will not let us list initialize variables of built-in type if the initializer might lead to the loss of information.

,但是我的编译器gcc v 4.7.1在以下代码中成功初始化了变量 a

but my compiler gcc v 4.7.1 initialized variable a in the following code successfully:

long double ld = 3.1415926536; 
int a{ld};

这里只是警告:将ld的转换范围从long long缩小为int {} [-缩小范围]。

there was just warning: narrowing conversion of ‘ld’ from ‘long double’ to ‘int’ inside { } [-Wnarrowing].

推荐答案

初始化列表的功能之一是不允许缩小范围的转换。但是语言定义并不能区分警告和错误。当代码格式错误时,它需要诊断,它被定义为一组实现定义的消息中的任何消息。警告满足此要求。这就是非标准扩展的机制:发出警告后,编译器可以自由执行任何其想做的事情,包括根据特定于实现的规则进行编译。

One of the features of initializer lists is that narrowing conversions are not allowed. But the language definition doesn't distinguish between warnings and errors; when code is ill-formed it requires "a diagnostic", which is defined as any message from a set of implementation-defined messages. Warnings satisfy this requirements. That's the mechanism for non-standard extensions: having issued a warning, the compiler is free to do anything it wants to, including compiling something according to implementation-specific rules.

这篇关于为什么编译器允许缩小转换范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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