Programmer
Programmer

Reputation: 6753

OR operator in C not working

I don't understand why the final printf in the code below is not printing 255.

char c;
c = c & 0;
printf("The value of c is %d", (int)c);
int j = 255;
c = (c | j);
printf("The value of c is %d", (int)c);

Upvotes: 4

Views: 492

Answers (4)

In most implementations the char type is signed, so it ranges from -128 to 127.

This means, 11111111 (which is 255 written in binary) is equal to -1. (As it's represented as a value stored in two's complement)

To get what you expect, you need to declare c as a unsigned char, like so:

unsigned char c = 0;
int j = 255;
c = (c | j);
printf("The value of c is %d", (int)c);

Upvotes: 16

raa one
raa one

Reputation: 33

By default char is signed char in C. If you want 255 to be printed then use unsigned char however i explain the output in context of signed char so that the concept becomes clear. If you write j=127 then it will print 127 as the bit representation is 01111111. But if you write j=128 then it will print -128 because the bit representation 01111111 has increased by 1 to become 10000000. now if you write j=255 then the bit representation is 11111111. so it will print -1 If you write j=256 then it will print 0 because when bit representation 11111111 is increased by 1 it becomes 100000000. But only 1 byte is allocated for a characher variable so the left most bit is not stored and bit representation becomes 00000000. Further if you write j=257 then its also a case of overflow and the bit representation become 00000001 and 1 will be printed.

Upvotes: 0

Andrei Bozantan
Andrei Bozantan

Reputation: 3941

Try to replace char c with unsigned char c. Basically char type supports values from -128 to 127. Your result is bigger than the supported range and overflows.

Upvotes: 2

Andrea Bergia
Andrea Bergia

Reputation: 5552

It is probably printing -1. That is because

c = (c | j);

will evaluate as

c = (0 | 255) = (0 | 0xFF) = 0xFF

but, since c is signed, 0xFF will be -1 and not 255 as you expected. If you change c to unsigned char it will print 255, as you imagined.

Upvotes: 5

Related Questions