Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for underflow/overflow in C++?

Is there a general way to check for an overflow or an underflow of a given data type (uint32, int etc.)?

I am doing something like this:

uint32 a,b,c;
... //initialize a,b,c
if(b < c) {
   a -= (c - b)
}

When I print a after some iterations, it displays a large number like: 4294963846.

like image 456
Legend Avatar asked Mar 08 '10 04:03

Legend


People also ask

How do you check if there is an overflow in C?

Write a “C” function, int addOvf(int* result, int a, int b) If there is no overflow, the function places the resultant = sum a+b in “result” and returns 0. Otherwise it returns -1. The solution of casting to long and adding to find detecting the overflow is not allowed.

What is an overflow error in C?

An integer overflow occurs when you attempt to store inside an integer variable a value that is larger than the maximum value the variable can hold. The C standard defines this situation as undefined behavior (meaning that anything might happen).


1 Answers

To check for over/underflow in arithmetic check the result compared to the original values.

uint32 a,b;
//assign values
uint32 result = a + b;
if (result < a) {
    //Overflow
}

For your specific the check would be:

if (a > (c-b)) {
    //Underflow
}
like image 191
Stephen L Avatar answered Sep 19 '22 01:09

Stephen L