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.

5/12/2016 3:22:36 PM

Accepted Answer

The != operator serves this purpose for bool values.

10/20/2009 7:03:38 PM

For a true logical XOR operation, this will work:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow