Possible Duplicate:
Best way to detect integer overflow in C/C++
i have tried to implement simple program which tests if overflow occurs during integer addition:
#include <climits>
#include <iostream>
#include <string>
using namespace std;
string overflow(long a,long b){
return ((a+b)>UINT_MAX)?"true":"false";
}
int main(){
long a, b;
cout << "enter a and b: ";
cin >> a >> b;
string m = overflow(a,b);
cout << m;
return 0;
}
UINT_MAX=65535 so i have entered 65535 and 20 but it wrote false why?
Given
unsigned int a, b, this expression can never evaluate totrue:The reason why it can’t ever be
trueis becauseUINT_MAXis the max, so whatever result(a+b)is can never be greater thanUINT_MAX, because that would be a contradiction.You tried to use a bigger data type
longto get around this, but this is actually not guaranteed to be bigger thanintin C++. You may want to trylong longinstead (although this type does not exist in standard C++).Unlike, say, Java, C++ does not actually specify how large each data type must be, so the claim that
UINT_MAX=65535is not universally true. It’s only true for processors where an unsigned integer is held in 16 bits. For 32 bits,UINT_MAXis4294967295.Related questions
See also