Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

    int f(int x, int y) {
       return x << y;
    }
This is undefined for SOME values of y, namely those bigger than 31 (on platforms where int is 32 bit; adjust where different).

This is caused by two facts:

a) The arithmetic operation should be compiled to a hardware shift instruction where possible

b) Different architectures do different things when shifting by an amount bigger than the word size:

- on ARM, the "y" operand is evaluated mod 32

- on x86, if y is greater than 31, the result is 0



> - on ARM, the "y" operand is evaluated mod 32

> - on x86, if y is greater than 31, the result is 0

You mixed them up, didn't you ?

AFAIK, ARM does set all bits to 0 if the shift if greater than 31, but it only uses the lowest byte of the shift amount register, so it feels like a mod 256.

x86[^1] does mask the lower 5 bits of the shift amount, so it feels like a mod 32. And the amount can only be 8 bits, so a 32-bit C variable must be truncated somehow.

[1] except on 8086, there is no mask there, so no modulo.




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: