1. 如何自己计算得到边界值
注:整数常量的数据类型默认为:能表示该数的最小数据类型。
以下从小到大排列,选择表中能够表示该整数常量的第一个数据类型(如 8 选 int,2^32+10 选 long int)
- 10进制常量可选:int, long int, long long int
- 8进制或16进制常量可选:int, unsigned int,long int,unsigned long int, long long int,unsigned long long int)
// 计算数据类型的边界:最小值和最大值
//
#include <iostream>
using namespace std;
int main()
{
//计算无符号整型
unsigned int uint_max, uint_min;
uint_max = ~(unsigned)0;//按位取反
uint_min = 0;
cout <<"uint_max = " << uint_max << endl;
cout <<"uint_min = " << uint_min << endl;
//计算有符号整型
int int_max, int_min;
int_max = (~(unsigned)0 >> 1) ;
int_min = -int_max - 1;
cout <<"int_max = "<< int_max << endl;
cout <<"int_min = "<< int_min << endl;
}
2. C/C++库文件的数据类型边界
在C语言中的各数据类型的边界如下:
包含在头文件#include <limits.h>
c++包含在#include <limits>
– 引用的是limits.h的内容
//limits.h
#define MB_LEN_MAX 5 /* max. # bytes in multibyte char */
#define SHRT_MIN (-32768) /* minimum (signed) short value */
#define SHRT_MAX 32767 /* maximum (signed) short value */
#define USHRT_MAX 0xffff /* maximum unsigned short value */
#define INT_MIN (-2147483647 - 1) /* minimum (signed) int value */
#define INT_MAX 2147483647 /* maximum (signed) int value */
#define UINT_MAX 0xffffffff /* maximum unsigned int value */
#define LONG_MIN (-2147483647L - 1) /* minimum (signed) long value */
#define LONG_MAX 2147483647L /* maximum (signed) long value */
#define ULONG_MAX 0xffffffffUL /* maximum unsigned long value */
#define LLONG_MAX 9223372036854775807i64 /* maximum signed long long int value */
#define LLONG_MIN (-9223372036854775807i64 - 1) /* minimum signed long long int value */
#define ULLONG_MAX 0xffffffffffffffffui64 /* maximum unsigned long long int value */
3. 如何判读溢出
参考传送门:
C语言的整型溢出问题:http://www.kuqin.com/shuoit/20140421/339376.html
#include <limits.h>
//有符号整型的判断溢出
void f(signed int si_a, signed int si_b) {
signed int sum;
/* Handle error */
if (((si_b > 0) && (si_a > (INT_MAX - si_b))) ||
((si_b < 0) && (si_a < (INT_MIN - si_b)))) {
return;
}
sum = si_a + si_b;
}
时间: 2024-09-29 10:38:36