lezebulon
lezebulon

Reputation: 7994

detect underflow/overflow error at runtime?

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

Upvotes: 2

Views: 1862

Answers (2)

Bukes
Bukes

Reputation: 3718

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

Upvotes: 2

Mark B
Mark B

Reputation: 96261

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.

Upvotes: 4

Related Questions