Hey
Hey

Reputation: 1841

Is it acceptable to use code that overflows but gives the correct result?

I want to subtract two user-supplied integers, and store the resulting range length. I obviously can't store it as an integer, as subtracting int.MaxValue and int.MinValue for example will overflow an int.

I wrote this :

uint rangeLength = (uint)max - (uint)min

It works in every case, but you can see that the cast will oveflow the uint type when one of the two integers is negative. However, this line gives the correct result.

This seems to do the same, doing two more operations, but without overflowing :

uint rangeLength = ((uint)max + int.MaxValue) - ((uint)min + int.MaxValue);

Is it acceptable to use the first line it in my code, or is it too confusing ? Should I use the second one just so that it doesn't seem like an error ?

Upvotes: 0

Views: 86

Answers (1)

Sweeper
Sweeper

Reputation: 271515

If it works in every case, then I think readability is the only thing you need to worry about.

You seem to have named your variables correctly - rangeLength. And you wrote that it is equal to max - min, so people probably will understand what you are doing. If you named the result a or something like that, then it's bad. If you are really worried, make it a method and abstract away the implementation details:

public uint RangeBetween(int max, int min) {
    return (uint)max - (uint)min;
}

uint rangeLength = RangeBetween(max, min);

Upvotes: 2

Related Questions