Bitwise OR not working C [duplicate]
Please help me with this code. I don't know why the output is not 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 &a开发者_开发百科mp; 1) == 1){
i++;
c = c>>1;
}
printf("the value of i is %d",i);
system("pause");
return 0;
}
To all the people who gave me -1, I tried printing the values. But it goes into an infinite loop.
As you learnt from your previous question, char
is signed on your platform. Therefore, at the beginning of your while
loop, c
has a negative value.
Right-shifting a negative value is implementation-defined. On your platform, I imagine it is doing an arithmetic shift.
This code has undefined behavior on the very first statement. c
is uninitialized and has an indeterminate value, and using an object with indeterminate value, even to bitwise-and or multiply it by zero, results in undefined behavior.
Try using an unsigned char
. The standard C char
can be signed (and quite often is on PC).
精彩评论