问题
On Visual Studio compiling following C code , the result is 4 .
void main() { int c = 1; c = c<<34;}
The assembly code as seen from on Visual Studio disassembly window is
shl eax,22h
From assembly , its easy to see that we are shifting 34. Since the integer here is 4 bytes , from the results it is obvious that modulo operation was carried out on machine level to make this work as shift by 2.
I was wondering if this behavior is standardized across platforms or varies across platforms?
回答1:
Undefined behavior happens. That's standardized by the language standard (See section 6.5.7 Bitwise shift operators
of the C standard from 1999). The observable effects of UB are not standardized, however, and may vary.
As for shl eax, 22h
, the shift count is going to be truncated to 5 bits by the CPU (see the documentation) and this instruction will really behave as shl eax, 2
.
回答2:
According to this article on MSDN:
The result is undefined if the right operand of a shift expression is negative or if the right operand is greater than or equal to the number of bits in the (promoted) left operand. No shift operation is performed if the right operand is zero (0).
来源:https://stackoverflow.com/questions/16122512/what-happens-if-we-bitwise-shift-an-integer-more-than-its-size