使用gcc进行逐位移位的意外行为

puf*_*der 3 c linux gcc bit-shift

我有一个这样的测试程序:

int main()
{
    unsigned n = 32;

    printf("ans << 32 = 0x%X\n", (~0x0U) << 32);
    printf("ans >> 32 = 0x%X\n", (~0x0U) >> 32);

    printf("ans << n(32) = 0x%X\n", (~0x0U) << n);
    printf("ans >> n(32) = 0x%X\n", (~0x0U) >> n);

    return 0;
}  
Run Code Online (Sandbox Code Playgroud)

它产生以下输出:

ans << 32 = 0x0  ... (1)  
ans >> 32 = 0x0  ... (2)  
ans << n(32) = 0xFFFFFFFF  ... (3)  
ans >> n(32) = 0xFFFFFFFF  ... (4)   
Run Code Online (Sandbox Code Playgroud)

我期望(1)和(3)是相同的,以及(2)和(4)是相同的.

使用gcc版本:gcc.real(Ubuntu 4.4.1-4ubuntu9)4.4.1

怎么了?

phi*_*hag 8

根据C标准 §6.5.7.3 ,按类型大小进行移位是未定义的行为:

6.5.7按位移位运算符
(...)如果右操作数的值为负或大于或等于提升的左操作数的宽度,则行为未定义.

您的编译器应该警告您:

$ gcc shift.c -o shift -Wall
shift.c: In function ‘main’:
shift.c:5:5: warning: left shift count >= width of type [enabled by default]
shift.c:6:5: warning: right shift count >= width of type [enabled by default]
Run Code Online (Sandbox Code Playgroud)

如果你看一下gcc正在生成的汇编程序代码,你会看到它实际上是在编译时计算前两个结果.简化:

main:
    movl    $0, %esi
    call    printf

    movl    $0, %esi
    call    printf

    movl    -4(%rbp), %ecx  ; -4(%rbp) is n
    movl    $-1, %esi
    sall    %cl, %esi       ; This ignores all but the 5 lowest bits of %cl/%ecx
    call    printf

    movl    -4(%rbp), %ecx
    movl    $-1, %esi
    shrl    %cl, %esi
    call    printf
Run Code Online (Sandbox Code Playgroud)

  • 再次阅读引用的规范.它说"大于或等于".根据规范,32位操作数上的32位移位未定义.处理器通常忽略除移位量的低5位之外的所有位,这会在这些处理器上产生"x << 32 == x",包括x86.在其他处理器上,零将被移入.C标准是灵活的,允许实现在所有处理器上执行快速操作. (3认同)