Bitwise Leftshift (<<) strange behavior

后端 未结 6 949
鱼传尺愫
鱼传尺愫 2021-01-15 13:41

gcc bitwise Leftshift (<<) strange behavior. Here is my code:

#include 
#include 

void foo(in         


        
6条回答
  •  渐次进展
    2021-01-15 14:16

    Shifting by a value that is equal or greater than the width of the promoted type of the left operand is undefined behaviour, so you must specifically test for and avoid this. In addition, a left-shift of a signed type that results in overflow is also undefined behaviour, so you need to also avoid a shift of 31, too:

    printf("1<<(32-n):%d\n", (n > 1 && n < 33) ? 1 << (32-n) : 0);
    

    This particular expression uses 0 for the cases that are otherwise undefined, but you can handle those differently if you need to.

提交回复
热议问题