按位或不工作C.

时间:2011-08-27 14:42:49

标签: c

请帮我这个代码。我不知道为什么输出不是8。

#include <stdio.h>
#include <stdlib.h>
int main(){
    char c;
    c = c & 0;
    printf("The value of c is %d", (int)c);
    int j = 255;
    c = (c | j);
    int i =0;
    while( (c & 1) == 1){
        i++;
        c = c>>1;
    }
    printf("the value of i is %d",i);
    system("pause");
    return 0;
}

对于给我-1的所有人,我尝试打印这些值。但它进入了一个无限循环。

3 个答案:

答案 0 :(得分:8)

your previous question了解到,char已在您的平台上签名。因此,在while循环开始时,c的值为负值。

对负值进行右移是实现定义的。在您的平台上,我想它正在进行arithmetic shift

答案 1 :(得分:3)

此代码在第一个语句中具有未定义的行为。 c未初始化且具有不确定的值,并且使用具有不确定值的对象,即使按位和/或将其乘以零,也会导致未定义的行为。

答案 2 :(得分:0)

尝试使用unsigned char。标准C char可以签名(通常在PC上)。