0

i have some code and it checking chechsum by XOR on 5 first numbers, and it should be equal to the sixth number. But, what is the difference between

if (n0^n1^n2^n3^n4==n5)  return true;
    else return false;

and

if ((n0^n1^n2^n3^n4)==n5)  return true;
    else return false;

?

Because the first one is working and the second one is not.

Featurea
  • 21
  • 6

2 Answers2

4

The C grammar establishes operator precedence with == having higher precedence than ^. So n0^n1^n2^n3^n4==n5 is equivalent to n0^n1^n2^n3^(n4==n5), which differs from (n0^n1^n2^n3^n4)==n5.

This is regarded by Kernighan and Ritchie and others as a mistake in the design of the C language, which occurred due to the history of its development.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
2

C Operator Precedence of operator == is higher than the precedence of the operator ^. Therefore in the first case the C compiler first executes n4==n5 which either results in 1or 0 and then it will do all xor operators between n0..n3 and the result of the comparison.

In the second case the precedence of the () is higher than '=='. So, all xor operators will be done first and the comparison will be done the last.

It explains the difference in your program results.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
Serge
  • 11,616
  • 3
  • 18
  • 28