FluorescentGreen5 FluorescentGreen5 - 2 months ago 9
C++ Question

Detect Integer Overflow Using If Statement

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 independent way of checking.

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)

Answer

It depends on what sort of operation you are using and what are the types of the operands.

e.g. if you want to detect an overflow after addition, and both operands are unsigned integers, then an overflow will have occurred if the result is less than the sum of both operands.

bool overflow;
if (a+b < a)
   overflow = true;
else
   overflow = false;

For signed integers, you can refer to the excellent post here

Comments