Efficient coding considered harmful?

K.LAUX rkl1 at hound.UUCP
Thu Nov 3 03:31:27 AEST 1988


In article <136 at twwells.uucp>, bill at twwells.uucp (T. William Wells) writes:
| In article <8775 at smoke.BRL.MIL> gwyn at brl.arpa (Doug Gwyn (VLD/VMB) <gwyn>) writes:
| : In article <119 at twwells.uucp> bill at twwells.UUCP (T. William Wells) writes:
| 
| : >... dividing positive numbers by powers of two should be done with a shift.
| :
| : No!  Juggling the source code to use bit-oriented operations in an
| : arithmetic context not only makes the code less portable and harder
| : to maintain, it can also lead to future errors, when for example a
| : chunk size is changed to a variable rather than a constant, or to a
| : non-power-of-two.
| 
| Less portable?
| 
| 	If a compiler doesn't take my n >> m (n >= 0, m < 16) and do
| 	the same thing as when dividing it by 2**m, the compiler is
| 	broken.  Now, there might be some compilers that are broken
| 	that way, but that makes it an individual decision as to
| 	whether one panders to the frailties of those compilers. For
| 	the record, the spelling code I earlier mentioned does this in
| 	a few places and I've never heard of a problem relating to it.
| 

	I'm suprized that noone has questioned the validity of shifting
instead of dividing by (powers of) 2.

	What about the difference between Logical and Arithmetic shifts?
If you want to divide, then divide!  A lot of compilers are smart enough
to implement the divide as a shift, but only where appropriate.

	I *did* notice the condition of dividend being positive, but now
you have to *guarantee* that it will always be positive.  Also, by
implication, the dividend is a *signed* quantity.  You can get into
trouble if it gets changed to an *unsigned* quantity (like when 16K isn't
enough).

	As for the 'compiler being broken' if it doesn't do the same thing
for a shift and dividing, this is not true.  In one case, you only told
it to shift, the other to do a divide:  they made be *equivalent*, but
they certainly are not *equal*.

	So, please, if you *functionally* require a divide by (powers of) 2,
code it as a divide and let the compiler *implement* it (maybe optimization
needs to be turned on).

--rkl



More information about the Comp.lang.c mailing list