《c陷阱与缺陷》笔记--注意边界值

来源:互联网 发布:java查询ip地址归属地 编辑:程序博客网 时间:2024/06/05 13:35

如果要自己实现一个获取绝对值的函数,应该都没有问题,我这边也自己写了一个:

void myabs(int i){        if(i>=0){                printf("%d\n",i);        }else{                printf("%d\n",-i);        }}

但是,这个函数真的没有问题吗?如果i的值为-2147483648,会怎样,我们来试下:

#include <stdio.h>void myabs(int i){        if(i>=0){                printf("%d\n",i);        }else{                printf("%d\n",-i);        }}int main(void){        int a = -2147483648;        myabs(a);        return 0;}

上面代码编译后出现如下warning:

unsigned.c: In function 'main':
unsigned.c:12:2: warning: this decimal constant is unsigned only in ISO C90 [enabled by default]

执行后的结果为:

-2147483648


额,怎么没有变成正数呢。因为32位系统int的范围为-2147483648 ~ 2147483647,负数比正数可容纳的值大了1,

所以-2147483648取反后就无法保存在int型变量中了。

原创粉丝点击