7

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?

Maroun
  • 94,125
  • 30
  • 188
  • 241
Manik Mahajan
  • 1,566
  • 2
  • 13
  • 19

2 Answers2

10

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.

Alexey Frunze
  • 61,140
  • 12
  • 83
  • 180
  • Where does it say that about truncation? http://download.intel.com/products/processor/manual/325462.pdf – Lefteris E Apr 20 '13 at 16:34
  • 2
    @LefterisE Right there, in `Vol. 2B`, section `SAL/SAR/SHL/SHR—Shift`: `The count operand can be an immediate value or the CL register. The count is masked to 5 bits (or 6 bits if in 64-bit mode and REX.W is used). The count range is limited to 0 to 31 (or 63 if 64-bit mode and REX.W is used).` Where were you looking for it and why? – Alexey Frunze Apr 20 '13 at 16:38
  • I wanted to confirm what you said to upvote your answer – Lefteris E Apr 21 '13 at 12:50
5

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).

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466