改善C程序代码的125个建议(一)

1.使用显示声明为 signed char或 unsigned char 的类型来执行算术运算
#include <stdio.h>
int main(void)
{
    char test_char=150;
    int test_div=900;
    printf("test_div/test_char=%d\n",test_div/test_char);
    return 0
}

该段程序在gcc和vs2010中返回值都是“-8”产生的原因在于机器自动将char类型转换为了 signed char类型,它的取值范围为(-127,127),“150”的取值超过了取值范围,机器中存储数值的方法是补码的方式,
+ 150的二进制表示:10010110
+ 150的反码表示: 11101001(首位1代表为负数)
+ 150的补码表示: 11101010
在运算过程中应该是又经过了自动类型转换将8位的char类型变成了int 类型(具体的转换过程未知)
所以读出的值为-106.可以参考下面的这一段代码

#include <stdio.h>
int main(void)
{
        signed char c=150;
        int i=900;
        int c_=(int)c;
        printf("%d\n",c_);
        printf("i/c=%d\n",i/c);
        return 0;
}
2.使用size_T来表示一个对象所占用空间的整数值单位

看接下来的这一段代码

#include <stdio.h>
int main(void)
{
        //extern and initial var
        int test_int_array[5]={1,2,3,4,5};
        size_t iterator;
        size_t lenth=5;

        //see the bytes the type of sizeof occupied
        printf("sizeof(size_t)=%d\n",sizeof(iterator));

        //test the sizeof type to be array's index
        for(iterator=0;iterator<lenth;iterator++)
        {
                printf("test_int_array[%d]=%d\n",iterator,test_int_array[iterator]);
        }

        return 0;
}

输出的结果为

sizeof(size_t)=8
test_int_array[0]=1
test_int_array[1]=2
test_int_array[2]=3
test_int_array[3]=4
test_int_array[4]=5

size_t可以很好的充当下标很长度的一些指标,需要注意的是不同平台的size_t类型的原始类型不一定相同,尽量不要和原始类型混用。

猜你喜欢

转载自www.cnblogs.com/bookdrip/p/10308538.html
今日推荐