Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for overflow condition in an arithmetic operation [duplicate]

Tags:

c++

c

Possible Duplicate:
Best way to detect integer overflow in C/C++

how do we check if any arithmetic operation like addition, multiplication or subtraction could result in an overflow?

like image 695
pravs Avatar asked Nov 28 '25 22:11

pravs


1 Answers

Check the size of the operands first, and use std::numeric_limits. For example, for addition:

#include <limits>

unsigned int a, b;  // from somewhere

unsigned int diff = std::numeric_limits<unsigned int>::max() - a;

if (diff < b) { /* error, cannot add a + b */ }

You cannot generally and reliably detect arithmetic errors after the fact, so you have to do all the checking before.

You can easily template this approach to make it work with any numeric type.

like image 184
Kerrek SB Avatar answered Dec 01 '25 12:12

Kerrek SB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!