Wednesday, December 2, 2009

When in doubt, use 0 instead of -1 for null

I use 16 bits in Albion to represent linetypes, which are looked up in a table. Since the dawn of time, I've had one special value for the 'continuous' linetype, which is -1. While unable to sleep in the summer heat and mosquitoes, I've realized that it would be perfect if I could repurpose the top 2 bits to encode the line cap style (butt, square, round, ?). But there is just no clean way to do this and still have -1 represent the 'continuous', aka default linetype.
I think the reason this problem exists is because in C, -1 is just two characters to type (and read), and so it is a concise way to represent null. If we were writing integer constants in binary, we wouldn't do this. The bits are likely to be useful in a way that is aligned to their positions, if only because a CPU is just so good at that, and the concept is so universal and easy to implement and understand.
So, long story short: All things being equal, use 0 for null, and not -1. From the point of view that an on bit represents information, zero is better aligned to 'nothing'.