Is shift count >= width undefined behavior?

-2

Following compiles with a warning.

I expected ff >> 40 to return 0, but it acts as UB. Is this defined as UB?

Is there any easy branch-less way to make it 0 or I should check shift value?
(I can branchless check shift value, but looks bad style at least for me)

#include <cstdint>
#include <cstdio>

int main(int argc, char **argv){
    uint32_t const ff = 0xffffffff;

    printf("%08x\n", ff >> 8    );
    printf("%08x\n", ff << 8    );
    printf("%08x\n", ff >> 40   );
    printf("%08x\n", ff << 40   );
}
c++
c
undefined-behavior
bit-shift
asked on Stack Overflow Nov 11, 2020 by Nick • edited Nov 11, 2020 by Scheff

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0