C陷阱——两int类型相加溢出问题

说明:

最近在统计线程时间时,发现一个问题
在这里插入图片描述,这个是大家很容易犯的错误,
int型加一int型,即使目标数是long long int型也会溢出,
需要再计算中加一个强制类型转换,如下程序所示

相关参考:数据类型范围速查表

char -128 ~ +127 (1 Byte)
short -32767 ~ + 32768 (2 Bytes)
unsigned short 0 ~ 65535 (2 Bytes)
int -2147483648 ~ +2147483647 (4 Bytes)
unsigned int 0 ~ 4294967295 (4 Bytes)
long long int -9223372036854775808 ~ +9223372036854775807 (8 Bytes)
unsigned long long int 0 ~ 18446744073709551615
double 0 ~ 1.7 * 10^308 (8 Bytes)

/***************************************************************************************
说明:最近在统计线程时间时,发现一个问题,这个是大家很容易犯的错误,
	  int型加一int型,即使目标数是long long int型也会溢出,
	  需要再计算中加一个强制类型转换,如下程序所示
时间:2020.1.14
作者:maoge

相关参考:数据类型范围速查表
char				                     -128 ~ +127 (1 Byte)
short								   -32767 ~ + 32768 (2 Bytes)
unsigned short								0 ~ 65535 (2 Bytes)
int								  -2147483648 ~ +2147483647 (4 Bytes)
unsigned int								0 ~ 4294967295 (4 Bytes)
long long int            -9223372036854775808 ~ +9223372036854775807 (8 Bytes)
unsigned long long int                      0 ~ 18446744073709551615
double                                      0 ~ 1.7 * 10^308 (8 Bytes)
****************************************************************************************/

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
	int value1 = 2147483447;//差一点溢出
	int value2 = 2147483447;
	unsigned long long int value3 = 0;
	unsigned long long int value4 = 0;
	value3 = value1 * 100 + value2 * 100;
	value4 = (unsigned long long int)value1 * 100 + (unsigned long long int)value2 * 100;

	printf("value3=%lld\n", value3);  //输出结果会溢出
	printf("value4=%lld\n", value4);  //输出正确
	return 0;
}

输出结果

在这里插入图片描述

发布了465 篇原创文章 · 获赞 694 · 访问量 96万+

猜你喜欢

转载自blog.csdn.net/mao_hui_fei/article/details/103979962