使用类型转换,除去gcc编译器警告 [英] Using typecasting to remove gcc compiler warnings

查看:1405
本文介绍了使用类型转换,除去gcc编译器警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做的用gcc 4.9嵌入式ARM编程。我一直在使用 -Wconversion 开关,因为它在我的公司的默认开发工具的配置。我使用stdint.h 类型(uint8_t有,uint32_t的,等等)。

编译器创建警告我每次执行一个复合赋值甚至是简单相加的时间。例如:

  uint8_t有U8 = 0;
uint16_t U16;//这些警告的原因:
U8 + = 2;
U8 = U16>> 8;

共同法来解决这个问题是使用强制类型转换,作为讨论的这里和的这里

  U8 =(uint8_t有)(U8 + 2);
U8 =(uint8_t有)(U16>→8);

除了这个是丑陋的,我一直运行到令人信服的证据表明铸件一般是不好的做法。

我的问题:


  1. 为什么不好以这种方式使用的类型转换?

  2. 请我简单地忽略 -Wconversion 键,让编译器失去任何东西为我做隐式转换?


解决方案

编译器正显示出你潜在的问题点,你应该考虑改变,但不能被强制转换。在code,你的问题是,在C,算术决不会在类型做到这一点比 INT 窄:编译器始终执行隐式转换为 INT 他们。

所以,有效地将code为转换窄无符号类型为 INT ,莫非操作,然后将它们转换回到无符号的类型。

窄类型一般是在做算术是不是一个好主意。仅当存储大小是一个问题(通常这将是较大的结构,例如数组)使用它们。对于本地,或多或少临时变量这些狭窄的类型没有任何意义。

I am doing embedded ARM programming with gcc 4.9. I've been using the -Wconversion switch because it's in my company's default dev tool configuration. I'm using the stdint.h types (uint8_t, uint32_t, etc).

The compiler creates warnings every time I perform a compound assignment or even simple addition. For example:

uint8_t u8 = 0;
uint16_t u16;

// These cause warnings:
u8 += 2;
u8 = u16 >> 8;

The "common method" to fix this is to use casts, as discussed here and here:

u8 = (uint8_t)(u8 + 2);
u8 = (uint8_t)(u16 >> 8);

In addition to this being ugly, I keep running into convincing evidence that casting is generally bad practice.

My questions:

  1. Why is it bad to use typecasts in this way?
  2. Do I lose anything by simply omitting -Wconversion and letting the compiler do implicit conversions for me?

解决方案

The compiler is showing you potential problem spots, that you should consider changing, but not by casts. The problem in the code that you have is that in C, arithmetic is never done on type that are narrower than int: the compiler always performs an implicit conversion to int for them.

So effectively your code is converting the narrow unsigned types to int, does the operation and then converts them back to the unsigned type.

Generally doing arithmetic with narrow types is not a good idea. Only use them if storage size is a problem (usually that would be larger structures such as arrays). For local, more or less temporary variables these narrow types make no sense.

这篇关于使用类型转换,除去gcc编译器警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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