Addressing Misconceptions: The precedence of C's shift operators

Randall Maas 5/16/2010 1:46:59 PM

What are the computed values, for the C/C++ language, of A and B below?

	unsigned A = 4 + 2 >> 1;
	unsigned B = 2 + 1 << 1;

Long ago I learned (the hard way) that the answers are 3 and 6, respectively. I expected 5 and 4. In other words, I expected the shift operators to have more precedence than addition and subtraction, but less than multiplication and division.

Since then I always add a rule to a projects coding style that the shift operations must be inside of a parenthesis (atleast if there are any operations to the left or right of it). And a rule that the left hand and right hand operands must be in parenthesis, if they are an expression. (That is to say, it must be "(4+2)" not "4+2".)

I am also pleased to report that lint and compilers, like Microsoft C's compiler, do give a warning. The bad news is that the error messages are pretty hard to understand:

warning C4554: '>>' : check operator precedence for possible error; use parentheses to clarify precedence

I wish that compilers would add flag to force this as an error.