FluorescentGreen5 - 8 months ago 42

C++ Question

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`

`if(c - b == a)`

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`

`unsigned long long`

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`

`<math.h>`

I am also aware that if I want an accurate

`int`

`pow`

`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