Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical XOR operator in C++?

Is there such a thing? It is the first time I encountered a practical need for it, but I don't see one listed in Stroustrup. I intend to write:

// Detect when exactly one of A,B is equal to five. return (A==5) ^^ (B==5); 

But there is no ^^ operator. Can I use the bitwise ^ here and get the right answer (regardless of machine representation of true and false)? I never mix & and &&, or | and ||, so I hesitate to do that with ^ and ^^.

I'd be more comfortable writing my own bool XOR(bool,bool) function instead.

like image 368
RAC Avatar asked Oct 20 '09 19:10

RAC


2 Answers

The != operator serves this purpose for bool values.

like image 62
Greg Hewgill Avatar answered Sep 19 '22 00:09

Greg Hewgill


For a true logical XOR operation, this will work:

if(!A != !B) {     // code here } 

Note the ! are there to convert the values to booleans and negate them, so that two unequal positive integers (each a true) would evaluate to false.

like image 40
LiraNuna Avatar answered Sep 19 '22 00:09

LiraNuna