Bluefire
Bluefire

Reputation: 14139

Count the number of overflows in an operation

From the large amount of questions on this topic, I know how to detect an overflow:

try {
    checked(doSomething());
} catch(OverflowException e) {
    //Handle overflow
}

However, is there a way to not just detect whether there has been at least one overflow, but to actually count how many overflows there were?

EDIT: to counter the misunderstandings, I don't want to just count how many operations lead to tone or more overflows, but how many overflows resulted from a certain operation.

Upvotes: 2

Views: 123

Answers (1)

Asik
Asik

Reputation: 22133

Assuming this is for integers, write a wrapper class for Int32 where you overload all the operators and sum the overflows in a static variable. Perform your overflow detection in these operators, the simplest (and slowest) is to go the checked/try-catch route, but if you need performance there are smarter alternatives (i.e. comparing signs).

Then replace int with your wrapper class everywhere.

Basic code structure:

struct CheckedInt {
     static int s_numOverflows = 0;
     int m_value;

     public CheckedInt(int value) { m_value = value; }
     public static CheckedInt operator +(CheckedInt x, CheckedInt y) {
         try { 
             return new CheckedInt(checked(x.m_value + y.m_value)); 
         }
         catch(OverflowException) { 
             ++s_numOverflows; 
             return new CheckedInt(unchecked(x.m_value + y.m_value)); 
         }
     }
     // ... etc for all operators, you'll also need to implement casts, IComparable(T), IEquatable(T), etc.
}

Upvotes: 3

Related Questions