If you ran the following code, what would you expect it to do?
	int sh = 33;
	printf("5 >> 33 = %d\n", 5 >> sh);
Reduced to looking at the last byte of an integer 5, we see that 00000101 >> 33 = 00000000. Right? Actually, it turns out, the answer is 2 (00000010). This is a consequence of the shift operation implementation in hardware: the operand to the shift command (on both Intel and SPARC assembly) is modulo the size of the data being operated on. So if you shift a 32-bit int by 32, you'll get no change, etc. This differs from the expected behavior in c. After all, (int)(5 / pow(2,32)) = 0, not 5. However, it turns out this would be pretty expensive for the compiler to correct for: virtually every shift would also be augmented by a conditional. And thus, for what I can only assume to be that reason, the C99 standard actually states that this behavior is undefined:

"The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined."
Comments:

You are absolutely correct. That's why it is a standard idiom to shift and mask...

Posted by Volker A. Brandt on August 10, 2007 at 02:04 AM PDT #

Post a Comment:
  • HTML Syntax: NOT allowed

This blog copyright 2007 by dank