简体   繁体   中英

What is the difference between XOR in parenthesis and without in C language

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.

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.

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 1 or 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM