The best is the enemy of the good

Once due to my inattention to details I wrote something like this:

	gWindowRect.right = gScreenCX - HORIZONTAL_MARGIN<<1;

Here I used C operator “<<” for integers where 2^N multiplication was needed because
I thought that shifting should be basically performed faster than multiplication.

However at least two pitfalls were hidden in this approach.
First problem, which actually caused the bug was the operator precedence.
Operator << has lower precedence than -, +, *, / operators so the code above should be re-written correctly:

	gWindowRect.right = gScreenCX - (HORIZONTAL_MARGIN<<1);


Another pitfal is noticed in MSDN:

	The results are undefined if the right operand of a shift expression is negative.
	The result of a right shift of a signed negative quantity is implementation dependent.


Since shifting negative values is simply not portable using shift operators to replace multiplication is
a very dangerous practice.
Actually modern compilers have no problems with optimization of constant arithmetic expressions
so this case is an example of how the best can be the enemy of the good.

Leave a Reply