2

Out of curiosity, is there any way to detect underflow/overflow errors for numbers at runtime? if no, why not? I know it can be the expected behavior but it would still be helpful I'm using Visual Studio 2010 if that changes anything

edit: for instance:

unsigned int a= 2;
unsigned int b= 3;
a -=b; //<- underflow
lezebulon
  • 7,607
  • 11
  • 42
  • 73

2 Answers2

4

C++ is a relatively lightweight language and as such doesn't provide any sort of automatic runtime checking for overflow/"underflow". Your code should generally be written in such a way that such things won't happen, and in cases where you're dealing with external input you'll need to guard the inputs with code specifically designed for the particular case you're protecting.

Mark B
  • 95,107
  • 10
  • 109
  • 188
2

Visual Studio includes an implementation of the SafeInt class which by default will raise an exception when an overflow/underflow occurs.

Bukes
  • 3,668
  • 1
  • 18
  • 20
  • 1
    I'm doing a little research on this, and thought I'd mention that besides having a variant that ships in Visual Studio, the library is hosted on codeplex and released under the ostensibly-permissive [Microsoft Public License](http://safeint.codeplex.com/license), and works in recent versions of gcc as well. – HostileFork says dont trust SE Jun 17 '12 at 04:58