James Hu said:
Can someone remind me what the on-topic lesson was? Here's my stab:
* For unsigned integral types, shift vs. multiply/divide by powers
of 2 are equivalent in C.
* For signed integral types, shift vs. multiply/divide by powers
of 2 in C depends on the implementation. If you want strictly
conforming code, you must use divide.
Did I get that right?
Not quite. For signed integral types, the result of a right shift for
negative numbers is implementation defined, and right shift by (n) is
usually not the same as division by 2^n. If you want a division, you
must divide. If you want a right shift, you must right shift. You
usually don't want a right shift.
Some people try to "optomize" by replacing division by a power of two
with a right shift. (I used the word "optomize" because it is usually
not a worthwhile optimization and a surprisingly high number of people
using this technique can't spell "optimize" correctly). The result: For
negative numbers, it is usually incorrect. For positive numbers, the
savings are tiny. For unsigned values, there is no saving.
You should also note that for negative numbers, you really have to
figure out what result you really want. C integer division rounds
towards zero (in C99. I think in C90 it was implementation defined for
negative values). However, quite often you want to round down, even for
negative values, and then a C division doesn't give the result you want.