Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion in evaluating == and &

Why does the below statement:

int a = 10;
a&8 == 8; 

return false (0) ?

I know that == has more precedence over &, but still it should check whether 8 == 8 and it should have evaluated true, but its evaluating as false.

Can anyone please help me through reasoning.

like image 363
Harikesh Avatar asked Aug 06 '13 08:08

Harikesh


7 Answers

a & 8 == 8 is a & (8 == 8) because == has higher precedence than & (here)

So 8 == 8 is 1 and a = 10 which is 1010 in binary

So

  00000001
& 00001010
  --------
  00000000

Interesting fact: Although false is a zero and true is any non-zero value in C Language. But, if the equality operator evaluates to be true it guarantees to evaluate to the value 1 and 0 otherwise. Referrer C99 Section 6.5.9 Paragraph 3

like image 108
phoxis Avatar answered Nov 15 '22 05:11

phoxis


The result of 8 == 8 when converted to int is 1.

a & 8 == 8 thus becomes a & 1, which is true if the least significant bit of a is set. This would only be true of a is odd.

Since a is 10, then a & 1 is 0, since 10 is even.

The & in this case is a bitwise-and and not a logical-and. A logical-and would have resulted in the expression a && 8 == 8 being true, since both sides of the && operator would have been non-zero.

However, the bitwise-and produces a result in which "each bit in the result is set if and only if each of the corresponding bits in the converted operands is set" (C.11 §6.5.10 ¶4). For an even number, the 1s bit is 0, so the result of bitwise-and with 1 is 0.

Since the result of the bitwise-and is 0, the expression is treated as false.

like image 25
jxh Avatar answered Nov 15 '22 04:11

jxh


Because 10 is 1010 in binary and result of 8 == 8 is 1. so 0001 & 1010 is false.

like image 26
Jeyaram Avatar answered Nov 15 '22 05:11

Jeyaram


a&8 == 8,

= a&1 // because 8 == 8, is true

= 0 // 1010 & 1 = 0
like image 3
mohit Avatar answered Nov 15 '22 03:11

mohit


Because 8 == 8 is true, which in C equals 1, 1 & 10 equals 0, which in C is false.

like image 2
jbr Avatar answered Nov 15 '22 05:11

jbr


As you are performing bitwise and(&) operation, a&1(8==8) is true,i.e 10 & 1 results to all 0's. O represents false.

00000000 00001010 & 00000000 00001000 = 00000000 00000000 = False (assumed int is 16 bit)

like image 1
Mahesh Avatar answered Nov 15 '22 04:11

Mahesh


a&8 == 8 is parsed as a & (8==8), which is the same as a & 1. Since a=10 is even its binary representation has a 0 in the units position, so the result of a & 1 is 0.

like image 1
Joni Avatar answered Nov 15 '22 05:11

Joni