1整数转换(包括隐式和显式(使用强制转换)),必须保证不会导致丢失或曲解数据。
C99规定:
a.当整数类型的值转换为另一个整数类型除了_Bool,如果该值可以被另一种类型表示,它的值是不变的。
b.否则如果新类型是无符号的,则该值是通过反复增加或减去MAX+1(MAX是新类型可表述的最大值),直到该值在新类型的范围内。
c.否则新类型是有符号的,该值不能用新类型表示;其结果要么是implementation-defined要么引发implementation-defined的信号。
Implementation-defined 指C99没有自己规定,但规定了编译器要明确规定,写在编译器文档中.
错误代码:
-
unsigned long int ul = ULONG_MAX;
-
signed char sc;
-
sc = (signed char)ul; /* cast eliminates warning */
代码中unsigned long int强制转换为signed char,导致数据被截断和符号错误。
正确代码:
-
unsigned long int ul = ULONG_MAX;
-
signed char sc;
-
if (ul <= SCHAR_MAX) {
-
sc = (signed char)ul; /* use cast to eliminate warning */
-
}
-
else {
-
/* handle error condition */
-
}
错误代码2:
-
signed int si = INT_MIN;
-
unsigned int ui;
-
ui = (unsigned int)si; /* cast eliminates warning */
si为INT_MIN转为unsigned int,导致数据错误和符号错误。
正确代码:
-
signed int si = INT_MIN;
-
unsigned int ui;
-
if ( (si < 0) || (si > UINT_MAX) ) {
-
/* handle error condition */
-
}
-
else {
-
ui = (unsigned int)si; /* cast eliminates warning */
-
}
错误代码3:
-
signed long int sl = LONG_MAX;
-
signed char sc;
-
sc = (signed char)sl; /* cast eliminates warning */
signed long int转换为signed char,导致数据截断。
正确:
-
signed long int sl = LONG_MAX;
-
signed char sc;
-
if ( (sl < SCHAR_MIN) || (sl > SCHAR_MAX) ) {
-
/* handle error condition */
-
}
-
else {
-
sc = (signed char)sl; /* use cast to eliminate warning */
-
}
错误代码4:
-
unsigned long int ul = ULONG_MAX;
-
unsigned char uc;
-
uc = (unsigned char)ul; /* cast eliminates warning */
unsigned long int转化为unsigned char,数据被截断。
正确:
-
unsigned long int ul = ULONG_MAX;
-
unsigned char uc;
-
if (ul > UCHAR_MAX) ) {
-
/* handle error condition */
-
}
-
else {
-
uc = (unsigned char)ul; /* use cast to eliminate warning */
-
}
阅读(781) | 评论(0) | 转发(0) |