Saturday, August 06, 2011

Checking for integer ranges - C# to C

I had tough time explaining what should be the correct mechanism for checking integer range for a developer coming from C# to C.

Intention is to check a value within the range of 0 to 4. Anything less than 0 and above four is invalid.

Expression written is

((http_method > -1) && (http_method < 5))

I wrote a review comment to change expression as

(Method >= 0) && (Method <= 4))

Comment is not accepted and led to a discussion, rather argument.

I said I have a problem with first part of expression

(http_method > -1)

The '-1' could be tricky depending upon type of http_method.

And in this case http_method is unsigned int and returned false even for correct range.

It took a while to explain the expression is invalid.

Though C# has an 'uint' type, an 'int' would suffice the need in most of the scenarios.

So using correct data type is one part of it. Also when it comes to checking ranges it is always recommended to check inclusive ranges rather than outer ranges. One simple reason for that is test cases. Test cases with inclusive range are considered as positive test cases and boundary range are considered as negative test cases.

Technically there is no binding to follow inclusive range check. But it is a good convention to follow.

No comments: