• 改善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
    ",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
    ",c_);
            printf("i/c=%d
    ",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
    ",sizeof(iterator));
    
            //test the sizeof type to be array's index
            for(iterator=0;iterator<lenth;iterator++)
            {
                    printf("test_int_array[%d]=%d
    ",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类型的原始类型不一定相同,尽量不要和原始类型混用。

    有符号和无符号混用的问题
    #include <stdio.h>
    int main(int argc,char * argv)
    {
            int array[]={1,2,3,4,5,6};
            int i = -1;
    
            printf("sizof(array)=%d
    ",sizeof(array));
            if( i <= sizeof(array))
            {
                    printf("i <= sizeof(array)
    ");
            }
            else
            {
                    printf("i >= sizeof(array)
    ");
            }
    
            return 0;
    }
    
    

    这段代码的结果可能会出乎我们的意料,代码的结果如下

    i >= sizeof(array)
    
    

    产生的原因在于有符号和无符号的类型在进行比较和运算的时候,会将有符号的整数类型自动转变为无符号的类型,这样会产生一些类型转换的问题。(尽量不要进行未知的隐性强制类型转换)

    无符号的整型不会产生溢出,但是溢出会产生回绕。
  • 相关阅读:
    关于隐藏元素高度的问题 css visibility:hidden 与 display:none的区别
    三星R428 内存不兼容金士顿2G DDR3
    IE (6-11)版本,在使用iframe的框架时,通过a标签javascript:; 和js跳转parent.location的时候 出现在新页面打开的情况
    按键精灵 vbs 获取网页源码 xp系统被拒绝
    threejs 组成的3d管道,寻最短路径问题
    javaweb部署多个项目(复制的项目)
    添加无登录权限的SSH用户命令
    Using Blocks in iOS 4: Designing with Blocks
    Using Blocks in iOS 4: The Basics
    Understanding Objective-C Blocks
  • 原文地址:https://www.cnblogs.com/bookdrip/p/10308538.html
Copyright © 2020-2023  润新知