2011-08-27 128 views
3

我有一个这样的测试程序:意外行为使用gcc

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; 
} 

它产生以下输出:

ans << 32 = 0x0 ... (1) 
ans >> 32 = 0x0 ... (2) 
ans << n(32) = 0xFFFFFFFF ... (3) 
ans >> n(32) = 0xFFFFFFFF ... (4) 

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

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

这是怎么回事?

+2

FWIW:http://ideone.com/RqWE9 –

回答

8

由类型的大小移是未定义的行为,根据C standard,§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] 

如果你看一下assembler code的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 
+0

我不是类型的多个大小移...我移等于类型 – puffadder

+0

@R的大小。 Martinho Fernandes哎呀,我的意思是大于*或等于*。更新并引用了标准。 – phihag

+0

现在更好+1。 @puffadder我希望这会教你启用并且不会忽略你的编译器警告;) –