Basic and Advance C Question:
I have been replacing multiplications and divisions with shift operators, because shifting is more efficient.
Answer:
This is an excellent example of a potentially risky and usually unnecessary optimization. Any compiler worthy of the name can replace a constant, power-of-two multiplication with a left shift, or a similar division of an unsigned quantity with a right shift. Furthermore, a compiler will make these optimizations only when they're correct; many programmers overlook the fact that shifting a negative value to the right is not equivalent to division. (Therefore, when you need to make sure that these optimizations are performed, you may have to declare relevant variables as unsigned.)
Previous Question | Next Question |
People claim that optimizing compilers are good and that we no longer have to write things in assembler for speed | Are pointers really faster than arrays? |