Bitwise Leftshift (<<) strange behavior

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

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

#include 
#include 

void foo(in         


        
6条回答
  •  情书的邮戳
    2021-01-15 14:19

    gcc is telling you what the problem is with the warning:

    main.c:5:3: warning: left shift count >= width of type [enabled by default]
    

    Your shifts need to be less than the size of the type otherwise it is undefined behavior. The C99 draft standard section 6.5.7 Bitwise shift operators paragraph 3 says:

    [...]If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

    Why is the first printf different from the second one? If you build using -fdump-tree-original you will see the following code generated for foo:

    printf ((const char * restrict) "1<<32:%d\n", 0);
    printf ((const char * restrict) "1<<(32-n):%d\n", 1 << 32 - n);
    

    It seems the first case it being optimized away to 0 which is consistent with undefined behavior, the compiler can do anything, including behavior that appears to work.

提交回复
热议问题