3

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?

Community
  • 1
  • 1
pravs
  • 371
  • 1
  • 4
  • 14
  • my question is specially towards unsigned integers – pravs Oct 28 '11 at 16:55
  • Strictly speaking, unsigned arithmetic does not overflow; it wraps around in a well defined manner. But that's just a quibble about the meaning of the word "overflow", and it doesn't answer your question. – Keith Thompson Oct 28 '11 at 18:42

1 Answers1

2

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • Hi,is there any method using some logic and without using any template to solve this problem? – pravs Oct 28 '11 at 17:00
  • 1
    I thought you could detect after: `a += b; if (a – Mooing Duck Oct 28 '11 at 17:00
  • 1
    @pravs: replace `std::numeric_limits::max()` with `UINT_MAX` – Mooing Duck Oct 28 '11 at 17:01
  • @pravs: I mean, you get the general idea, but using `numeric_limts` is by far the most uniform, readable, self-explanatory and portable way. Is there any reason *not* to use it? You could also say "is there a way to write C++ without classes or `for` loops"... but why? – Kerrek SB Oct 28 '11 at 17:03
  • i am unaware about "numeric_limits".could you suggest me some source from where i could get the idea? – pravs Oct 28 '11 at 17:07
  • 2
    @pravs: I did add a link, just click on it. Otherwise, read any decent C++ book to learn more about the language -- the FAQ has a good list, I believe. If all else fails, Stroustrup's book is always a good idea. I'd also suggest that you don't design your life around the "avoid anything I don't know yet" idea, but rather go for "how do I learn how to do things better?". :-) – Kerrek SB Oct 28 '11 at 17:09