2010/07/22

Home on the range

Posted in Code, CodeProject tagged , , at 18:13 by Orjan

Continuing on the train of thought started in bounds class I presented a few days ago in Bounds, and staying within them.

As so often happens, just having bounds available made me think of what variants of it could be useful. For instance, it would be handy to have it work for floating point or non-POD types, which isn’t possible as it is written. Since the bounds class uses ‘non-type template parameters‘ for its limits, only integer types and enums are accepted.[1]

Even disregarding this restriction, I found that I had use for a dynamic range class, as opposed to the static bounds which has its boundaries set at compile time. Just a simple one, and like std::pair only having two values, but with both of the same type, and with them guaranteed to be ordered.

The last part there would make it a bit more complex than the simple std::pair struct, as I’d need to validate the values given in order to ensure that the minimum was lower than or equal to the maximum, but still, a simple enough little class. Read on…

2010/07/12

Bounds, and staying within them

Posted in Code, CodeProject tagged , , at 13:39 by Orjan

How often have you written a line of code that looks something like this?

if (3 <= var && 14 >= var)

There might (read “should”) be named constant variables instead of the magic numbers there, but in essence it’s a very common piece of code for a very common type of test – is this value within pre-defined, constant bounds?

Some years ago, I was working on a project that had lots of tests like that, and I came across a surprisingly large number of errors one can commit with this simple code. For instance:

// non-paired constants
if (minTempUK <= var && maxTempUS >= var)

// wrong comparison 
if (minTempUK < var && maxTempUK >= var)

// test wrong way around  
if (maxTempUK <= var && minTempUK >= var)

// maxTempUK is compared to bool  
if (minTempUK <= var <= maxTempUK)

// bitwise rather than logical AND    
if (minTempUK <= var & maxTempUK >= var)  

All of these are legal C++, and only the last two or three might generate compiler warnings. The last would still work properly, but is a bit iffy. If it isn’t a typo, someone needs to read up on operators. In most cases, these errors were typos (except the fourth, which was written by someone more used to other languages), but since they compiled, and sort of worked, they only showed up as bugs every now and then, at the edge cases. And because the code looks sort of okay, it was hard to spot the typos right away.

Read on…

Follow

Get every new post delivered to your Inbox.