C 为什么这两种将变量设置为所有1的方法会导致不同的结果?

C 为什么这两种将变量设置为所有1的方法会导致不同的结果?,c,C,我最近发现,在C中,将变量设置为所有1的两种方法之间存在差异。 下面是一个小代码示例,用于说明我的64位Linux系统上的奇怪行为 // compile with `gcc -o weird_shift_behaviour weird_shift_behaviour.c` #include <stdio.h> int main(void){ long long foo = 0; long long bar = 0; int i; puts("<

我最近发现,在C中,将变量设置为所有1的两种方法之间存在差异。 下面是一个小代码示例,用于说明我的64位Linux系统上的奇怪行为

// compile with `gcc -o weird_shift_behaviour weird_shift_behaviour.c`

#include <stdio.h>

int main(void){
    long long foo = 0;
    long long bar = 0;
    int i;
    puts("<foo> will be set to all 1s by repeatedly shifting 1 to the left and OR-ing the result with <foo>.");
    puts("<bar> will be set to all 1s by repeatedly OR-ing it with 1 and shifting <bar> to the left one step.");
    for(i=0;i<8*(int)sizeof(long long)-1;++i){
        foo |= (1<<i);
        bar = bar<<1 | 1;
        printf("<i>: %02d <foo>: %016llx <bar>: %016llx \n",i,foo,bar);
    }
    return 0;
}
//使用`gcc-o-weird\u-shift\u-behavior-weird\u-shift\u-behavior.c编译`
#包括
内部主(空){
长foo=0;
长杆=0;
int i;
puts(“将通过反复向左移动1或用“.”将结果置为所有1);
puts(“将通过重复或使用1将其设置为所有1,并向左移动一步。”);

对于(i=0;i
1@coffeeholic:无
int
最大宽度为4字节。在64位系统上
long
为8字节宽。请使用
sizeof
@coffeeholic
int
检查它是否至少为16位宽,并且在64位系统中很可能为32位宽(除非在某些特殊的Cray系统中为64位).w00t,你说得对,即使在64位系统上,int也只有4个字节宽。看起来我并不是最聪明的人。不,这取决于实现,但在Visual Studio编译x64时,
int
确实是4个字节。我很抱歉,我明显、公然且不可原谅地缺乏对C的深入理解,这导致了这个问题。
<i>: 29 <foo>: 000000003fffffff <bar>: 000000003fffffff 
<i>: 30 <foo>: 000000007fffffff <bar>: 000000007fffffff 
<i>: 31 <foo>: ffffffffffffffff <bar>: 00000000ffffffff 
<i>: 32 <foo>: ffffffffffffffff <bar>: 00000001ffffffff 
1<<i