I'm just wondering if there is a logical XOR operator in C (something like && for AND, but for XOR). I know that I can split XOR into AND, NOT and OR, but a simple XOR would be much better. Then it occurred to me that if I use the usual bitwise XOR operator between two conditions, it might just work. And for my tests this was done.
Consider:
int i = 3; int j = 7; int k = 8;
Just for this rather stupid example, if I need k to be more or more than j, but not both, XOR would be very convenient.
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". Bringing the results of two comparisons into two integers led to the fact that 2 integers contained 1, so XOR produced a false. Then I tried this with and and | bitwise operators and both gave the expected results. All this makes sense, knowing that true conditions have non-zero values, while false conditions have zero values.
I was wondering if there is a reason to use boolean && and || when the bitwise operators &, | and ^ work the same?
c bitwise-operators logical-operators xor
reubensammut
source share