代码改变世界

Warinig C4244 and integral promotion

2006-10-11 18:47  atempcode  阅读(560)  评论(0编辑  收藏  举报
今天按照公司的code standard, 把一个project开到warning W4编译了一下, 一堆warning. 其中有一个很有趣.

typedef byte BYTE;
BYTE by;
BYTE bChecksum;

bChecksum 
+= by;

在 最后一行有warning C4244:
warning C4244: '+=' : conversion from 'int' to 'BYTE', possible loss of data.

hoho, 都是BYTE, 有int什么事. 翻开MSDN查一查吧. 原来编译器还真的会把BYTE转成int来的, 还有个名词叫"integral promotion":

A character, a short integer, or an integer bit field, all either signed or not, or an object of enumeration type, can be used in an expression wherever an integer can be used. If an int can represent all the values of the original type, then the value is converted to int; otherwise, it is converted to unsigned int. This process is called "integral promotion."

就是说如果int可以表示原来type的值, 编译器会自动把原来的值转成int型.

有人要说这不是多此一举嘛. 看看下面的code也许就不会怎么想了:

1 typedef byte BYTE;
2 BYTE by = 0xff;
3 BYTE by2 = 0xff;
4 int bChecksum;
5 bChecksum = by+by2;

bCheckSum等于多少? 应该是510吧. 但是如果没有integral promotion, by和by2都是byte, 计算结果也应该是byte, 那就是0xfe, 254了.

看来我要在这一行前加上 #pragma warning (disable : 4244) 了...