Over the summer I happened across a brief blog post by another firmware developer in which he presented ten of his C coding rules for better embedded code. I had an immediate strong negative reaction to half of his rules and later came to dislike a few more, so I'm going to describe what I don't like about each. I'll refer to this author as BadAdvice. I hope that if you have followed rules like the five below my comments will persuade you to move away from those toward a set of C coding rules that keep bugs out of your embedded software.
Bad Rule #1: Do not divide; use right shift.
As worded, the above rule is way too broad. It's not possible to always avoid C's division operator. First of all, right shifting only works as a substitute for division when it is integer division and the denominator is a power of two (e.g., right shift by one bit to divide by 2, two bits to divide by 4, etc.). But I'll give BadAdvice the benefit of the doubt and assume that he meant to write that you should "Use right shift as asubstitute for division whenever possible". This, of course, is unnecessary in many cases as a good optimizing compiler can also see that you are dividing by a fixed power of 2 and shift accordingly if that is faster on the target processor.For his example, BadAdvice shows code to compute an average over 16 integer data samples, which are accumulated into a variable sum, during the first 16 iterations of a loop. On the 17th iteration, the average is computed by right shifting sum by 4 bits (i.e., dividing by 16). Perhaps the worst thing about this example code is how much it is tied to a pair of #defines for the magic numbers 16 and 4. A simple but likely refactoring to average over 15 instead of 16 samples would break the entire example–you'd have to change from the right shift to a divide proper. It's also easy to imagine someone changing the first #define from 16 to 15 without realizing the significance of the second; in which case, you'd get a subtle bug in that the sum of 15 samples would still be divided by 16.
Better Rule: Shift bits when you mean to shift bits and divide when you mean to divide.
To read the entire article, click here.