小编cof*_*lic的帖子

为什么这两种方法将变量设置为全1会产生不同的结果?

我最近发现了将变量设置为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>: …
Run Code Online (Sandbox Code Playgroud)

c

5
推荐指数
1
解决办法
53
查看次数

标签 统计

c ×1