C ++ 11变量缩小,不带GCC编译器警告 [英] C++11 Variable narrowing with no GCC compiler warning

查看:142
本文介绍了C ++ 11变量缩小,不带GCC编译器警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

变窄的概念看起来很简单。

The concept of narrowing seems pretty straight-forward. However, could someone please explain why some of the code below causes "narrowing" compiler errors and others don't?

这段代码会产生预期的错误:

This code produces errors where expected:

constexpr int a = 255;
unsigned char b = a;      // OK
unsigned char c = a + 1;  // Error... expected

此代码不会产生错误, / p>

This code doesn't produce errors, but may be ok:

int d = 256;
unsigned char e = d;  // Maybe OK because 'd' is not constexpr

这段代码应该会产生错误缺少某物):

This code should generate errors (unless I'm missing something):

int f = 42.0;  // Maybe OK because no fractional part
int g = 42.1;  // OK... should fail!!
constexpr float h = 42.7;
int i = h;     // OK... should fail???

我使用的是g ++ 4.6.2。我搜索了GCC错误数据库,没有发现任何相关的。非常感谢!

I'm using g++ 4.6.2. I searched the GCC bug database and didn't find anything related. Thanks!

推荐答案

老实说,对于你的样本,我觉得没什么错。

To be honest, with your samples I see little wrong.

但是,有一些情况下,编译器似乎接受违反标准转换规则...:

However, there are a number of cases where the compiler seems to accept 'violations' of the standard conversion rules...:

但是我在标准中发现了这个:

However I spotted this one in the standard:

对于initialzer列表,

For initialzer lists, the following is not allowed (§ 8.5.4, under 3.)

int ai[] = { 1, 2.0 }; // error narrowing

6。例子列表:


[注意:如上所述,列表初始化中不允许在顶级进行此类转换。 -end
note]



int x = 999; // x is not a constant expression
const int y = 999;
const int z = 99;
char c1 = x; // OK, though it might narrow (in this case, it does narrow)
char c2{x}; // error: might narrow
char c3{y}; // error: narrows (assuming char is 8 bits)
char c4{z}; // OK: no narrowing needed
unsigned char uc1 = {5}; // OK: no narrowing needed
unsigned char uc2 = {-1}; // error: narrows
unsigned int ui1 = {-1}; // error: narrows
signed int si1 =
{ (unsigned int)-1 }; // error: narrows
int ii = {2.0}; // error: narrows
float f1 { x }; // error: might narrow
float f2 { 7 }; // OK: 7 can be exactly represented as a float
int f(int);
int a[] = { 2, f(2), f(2.0) }; // OK: the double-to-int conversion is not at the top level

有趣的是,g ++ 4.6 .1 - std = c ++ 0x -Wall -pedantic 仅捕获仅有一个

Interestingly, g++ 4.6.1 with --std=c++0x -Wall -pedantic catches only one of these violations:

    char c3{y}; // warning: overflow in implicit constant conversion [-Woverflow]






外部初始化列表...



我不认为将一个float截断为int是缩小

这只是一个定义明确的转换,很像

It is just a well-defined conversion, much like

int i = 31;
i /= 4;   // well defined loss of precision...   
i /= 4.0; // equally well-defined conversion from floating point to int

这篇关于C ++ 11变量缩小,不带GCC编译器警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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