reference:
http://www.geeksforgeeks.org/check-for-integer-overflow/
Problem Definition:
Write a “C” function, int addOvf(int* result, int a, int b) If there is no overflow, the function places the resultant = sum a+b in “result” and returns 0. Otherwise it returns -1. The solution of casting to long and adding to find detecting the overflow is not allowed.
Solution:
There can be overflow only if signs of two numbers are same, and sign of sum is opposite to the signs of numbers.
1) Calculate sum
2) If both numbers are positive and sum is negative then return -1
Else
If both numbers are negative and sum is positive then return -1
Else return 0
Code:
/* Takes pointer to result and two numbers as
arguments. If there is no overflow, the function
places the resultant = sum a+b in “result” and
returns 0, otherwise it returns -1 */
int addOvf(int* result, int a, int b)
{
*result = a + b;
if(a > 0 && b > 0 && *result < 0)
return -1;
if(a < 0 && b < 0 && *result > 0)
return -1;
return 0;
}
本文介绍了一种不使用长整型转换的方法来检测两个整数相加是否会发生溢出,并提供了一个 C 语言函数实现。该函数通过比较操作数的符号和结果的符号来判断是否有溢出发生。
2296

被折叠的 条评论
为什么被折叠?



