Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of the logical operators in C?

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?

like image 514
reubensammut Avatar asked May 05 '10 12:05

reubensammut


1 Answers

You don't need logical XOR, I have forgotten the SO question, but it's similar to what you're thinking, basically we don't need XOR, it's equivalent to != anyway

FALSE XOR FALSE == FALSE
FALSE XOR TRUE == TRUE
TRUE XOR FALSE == TRUE
TRUE XOR TRUE == FALSE


FALSE != FALSE == FALSE
FALSE != TRUE == TRUE
TRUE != FALSE == TRUE
TRUE != TRUE == FALSE

I'll search my favorites, and paste here the link later...

like image 116
Michael Buen Avatar answered Oct 04 '22 20:10

Michael Buen