Edit (IMPORTANT): This question was more specific than the question this was marked as a duplicate against. This was asking how to do it with a boolean function. But now I know that it just doesn't work like that. This question shows that a + b = c
can only be overflow checked if you write if(c - b == a)
and that there is no operator independent way of checking.
Once the overflow happened, you cannot detect it
-lorro
I have been looking for a way to detect integer overflow in C++ using an if statement.
Possible pseudo code:
#include <iostream>
#include <...>
using namespace std;
bool isOverflow(...);
int main()
{
int a = INT_MAX + 1;
if (isOverflow(...))
{
cout << "Overflow" << endl;
}
else
{
cout << "No Overflow" << endl;
}
return 0;
}
bool isOverflow
{
...
}
OK to be honest this pseudo code preference may not work, but i've seen this question asked many times and have not found any useful answers. It may require unsigned
or unsigned long long
, although I'm not necessarily encouraging the use of those.
EDIT:
I would like to use it with a multiplication sentence with 3 numbers:
a * a * b
I am aware that there is a pow
function in <math.h>
but that's off topic.
I am also aware that if I want an accurate int
result from pow
I would use:
int(pow(base, index) + 0.5)