浅谈溢出

来源:互联网 发布:端口号 进程 编辑:程序博客网 时间:2024/06/05 11:41
#include <stdio.h>#include <stdlib.h>#include <math.h>#define MAX_INT ((unsigned)(-1) >> 1)#define MIN_INT (MAX_INT + 1)int main(){  int n=2147483647;  printf("%d",n+1);    return 0;}

输出:-2147483648


实际上:如果整型超过了范围,则实际输出的应该是该数无符号范围最大值MOD的结果

#include <stdio.h>#include <stdlib.h>#include <math.h>#define MAX_INT ((unsigned)(-1) >> 1)#define MIN_INT (MAX_INT + 1)int main(){  int n=2147483650;  printf("%d",n);return 0;}

在codeblocks中 int占4个byte
范围是0~4294967296

故结果应为2147483650-4294967296=-2147483646


-2147483646Process returned 0 (0x0)   execution time : 0.036 sPress any key to continue.

0 0