What is the point of the logical operators in C?
Posted
by reubensammut
on Stack Overflow
See other posts from Stack Overflow
or by reubensammut
Published on 2010-05-05T12:37:51Z
Indexed on
2010/05/30
12:22 UTC
Read the original article
Hit count: 379
I was just wondering if there is an XOR logical operator in C (something like && for AND but for XOR). I know I can split an XOR into ANDs, NOTs and ORs but a simple XOR would be much better. Then it occurred to me that if I use the normal XOR bitwise operator between two conditions, it might just work. And for my tests it did.
Consider:
int i = 3;
int j = 7;
int k = 8;
Just for the sake of this rather stupid example, if I need k to be either greater than i or greater than j but not both, XOR would be quite handy.
if ((k > i) XOR (k > j))
printf("Valid");
else
printf("Invalid");
or
printf("%s",((k > i) XOR (k > j)) ? "Valid" : "Invalid");
I put the bitwise XOR ^ and it produced "Invalid". Putting the results of the two comparisons in two integers resulted in the 2 integers to contain a 1, hence the XOR produced a false. I've then tried it with the & and | bitwise operators and both gave the expected results. All this makes sense knowing that true conditions have a non zero value, whilst false conditions have zero values.
I was wondering, is there a reason to use the logical && and || when the bitwise operators &, | and ^ work just the same?
Thanks Reuben
© Stack Overflow or respective owner