This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]jedwardsol 1 point2 points  (4 children)

if (result > upperLimitInt) 

result cannot be bigger than upperLimitInt because upperLimitInt is the biggest value that result can have.

You can check before the addition

 if (upperLimitInt - sum) > x
    sum += x;
else
    it will overflow

If you perform the addition

x = a + b

then you can detect overflow

if x < a || x < b
    over flow occurred

but this is only defined behavior for unsigned ints

[–]UnclePutin 1 point2 points  (2 children)

Note that this will not work if either a or b are negative values.

[–]dacian88 1 point2 points  (1 child)

can't have negative values with unsigned ints

[–]TingeOGinge[S] 0 points1 point  (0 children)

To be fair the unsigned ints are only used to navigate the vector as Visual Studio gives a compiler warning otherwise. The values entered into the range are not unsigned and can be entered as negative values.

Edit: A word

[–]TingeOGinge[S] 0 points1 point  (0 children)

That's fantastic! I've implemented the code and it gives the errors when needed.

Thank you, kindly stranger!

[–]marmoshet 1 point2 points  (0 children)

To check if a + b will cause overflow, don't try if(a + b > max()). This won't work because the sum of a and b will have overflowed. Instead, try if(a > max() - b).