L
linq936
I have some algorithm dealing with unsigned int calculation a lot, I am
trying to add some check for overflow. The initial thinking was very
easy, just do something like this,
int addition(unsigned int i1, unsigned int i2) {
if ( i1 + i2 < i1 || i1 + i2 < i2 ) {
...throw some expception...
}
return i1+i2;
}
I also define a minus function doing similar thing, but for simplicity,
I only show addition functin here.
But it does not work as I expected. For example I have the following
code,
unsigned int base=0xFFFF0000
unsigned len=0x10000
unsigned int high= addition(base,len)-1;
you can see that an exception is thrown since 0xFFFF0000 + 0x10000 is
0x0, but it is what I expect.
i know I can adjust the above equation to addition(base-1, len), but
for the real code, there are a lot of really long plus and minus mixed
calculation. I guess there is no universal rule to break addition and
minus.
So the question is, for addition-minus-mixed calculation, is there any
way to ignore overflow in the middle and only catch it at the end?
trying to add some check for overflow. The initial thinking was very
easy, just do something like this,
int addition(unsigned int i1, unsigned int i2) {
if ( i1 + i2 < i1 || i1 + i2 < i2 ) {
...throw some expception...
}
return i1+i2;
}
I also define a minus function doing similar thing, but for simplicity,
I only show addition functin here.
But it does not work as I expected. For example I have the following
code,
unsigned int base=0xFFFF0000
unsigned len=0x10000
unsigned int high= addition(base,len)-1;
you can see that an exception is thrown since 0xFFFF0000 + 0x10000 is
0x0, but it is what I expect.
i know I can adjust the above equation to addition(base-1, len), but
for the real code, there are a lot of really long plus and minus mixed
calculation. I guess there is no universal rule to break addition and
minus.
So the question is, for addition-minus-mixed calculation, is there any
way to ignore overflow in the middle and only catch it at the end?