mvoiers
asked on
Check if an int has overflowed
If an int recieves a number which is to big, the extra bits get truncated, and the resulting number can be either positive or negative. Is there a way to check to see if this has happened? I know I can use a double which would simply go to infinity if such a thing was to happen but I am trying to deal with ints.
You can use
UINT_MAX
INT_MAX
....const
UINT_MAX
INT_MAX
....const
ASKER
Maybe I was not clear. I did state that I wanted to deal with ints and not doubles and the above solution clearly deals with doubles. I realize I could use a double and then compare it to INT_MAX but then I would be using a double and not an int. Say for example,
int x;
cin>>x;
cout<<x;
if the user types in INT_MAX+1 the value printed will be -INT_MAX. Is there a way to check between the cin and cout statements that the user entered a value for int greater then int_max?
There is no way to get C++ to throw an exception is an int overflows?
int x;
cin>>x;
cout<<x;
if the user types in INT_MAX+1 the value printed will be -INT_MAX. Is there a way to check between the cin and cout statements that the user entered a value for int greater then int_max?
There is no way to get C++ to throw an exception is an int overflows?
What OS are you using? Win32 raises a EXCEPTION_INT_OVERFLOW (SEH, not C++) in this case...
ASKER
I am using Solaris. This is a little practice assignment at work, we need to maintain portability and also ANSI C standards.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Ok...I guess I got my answer. I was really trying to get at the fact that if I have a function that takes an int and someone passes in something huge there is no way for that function to check if it has overflowed, unlike double which just goes to INFINITY.
What do you mean by "someone" if you mean a fucntion that calls your function, well that function has to pass an int, so it can't pass anythign larger than an int. Overflows don't occur this way, then occur when you perform calculations or when you assign a value to a "smaller" number. You can test for errors in these circumstances.
>>jkr, I don't think that is true
"EXCEPTION_INT_OVERFLOW
The result of an integer operation caused a carry out of the most significant bit of the result."
(See help on 'GetExceptionCode()')
"EXCEPTION_INT_OVERFLOW
The result of an integer operation caused a carry out of the most significant bit of the result."
(See help on 'GetExceptionCode()')
But I don't think it is being used is it? The x86 CPU doesn't cause an exception when this happens (probably no CPUs do.) so this would have to be manually tested for every time an int is manipulated in a way that this could happen. That is a lot of work and it is not done in the VC code I've seen.
Hmm, you're right - tested it and it didn't work ;-)
if(doub>0xFFFFFFFF)
......