1

I found some wired problems when I tried to do left shift for 32 times. The code in the test function should print the same results of 0x0, but I got "ffffffff, 0" instead. Anybody could give a hint of what's wrong with the code? Thank you!

int test(int n) {
    int mask = ~0 << (32 + ~n + 1);
    int mask1 = ~0 << (32 + ~0 + 1);
    printf("%x, %x\n", mask, mask1);
    return mask;
}

int main(){
    test(0);
}
zhengbli
  • 702
  • 5
  • 24
  • same with http://stackoverflow.com/questions/3784996/why-does-left-shift-operation-invoke-undefined-behaviour-when-the-left-side-oper – MOHAMED May 07 '13 at 16:30
  • Can you try making the int declaration an unsigned int and tell us if it will make any difference? – Manolis Ragkousis Jan 07 '14 at 19:54

2 Answers2

4

In C, shifting with size greater than the type size (int in your case) is an undefined behavior

From this topic: Relevant quote from ISO C99 (6.5.7/4)

The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 × 2E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 × 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

Community
  • 1
  • 1
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
2

Assuming you have 32-bit integers, the results of left shifting more than 31 times are undefined

From C11 §6.5.7 Bitwise shift operators

The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 x 2E2 , reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 x 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

simonc
  • 41,632
  • 12
  • 85
  • 103