What is the point of the logical operators in C?
- by reubensammut
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