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 wh
The !=
operator serves this purpose for bool
values.
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
.
I use "xor" (it seems it's a keyword; in Code::Blocks at least it gets bold) just as you can use "and" instead of &&
and "or" instead of ||
.
if (first xor second)...
Yes, it is bitwise. Sorry.
#if defined(__OBJC__)
#define __bool BOOL
#include <stdbool.h>
#define __bool bool
#endif
static inline __bool xor(__bool a, __bool b)
{
return (!a && b) || (a && !b);
}
It works as defined. The conditionals are to detect if you are using Objective-C, which is asking for BOOL instead of bool (the length is different!)
Use a simple:
return ((op1 ? 1 : 0) ^ (op2 ? 1 : 0));
There is another way to do XOR:
bool XOR(bool a, bool b)
{
return (a + b) % 2;
}
Which obviously can be demonstrated to work via:
#include <iostream>
bool XOR(bool a, bool b)
{
return (a + b) % 2;
}
int main()
{
using namespace std;
cout << "XOR(true, true):\t" << XOR(true, true) << endl
<< "XOR(true, false):\t" << XOR(true, false) << endl
<< "XOR(false, true):\t" << XOR(false, true) << endl
<< "XOR(false, false):\t" << XOR(false, false) << endl
<< "XOR(0, 0):\t\t" << XOR(0, 0) << endl
<< "XOR(1, 0):\t\t" << XOR(1, 0) << endl
<< "XOR(5, 0):\t\t" << XOR(5, 0) << endl
<< "XOR(20, 0):\t\t" << XOR(20, 0) << endl
<< "XOR(6, 6):\t\t" << XOR(5, 5) << endl
<< "XOR(5, 6):\t\t" << XOR(5, 6) << endl
<< "XOR(1, 1):\t\t" << XOR(1, 1) << endl;
return 0;
}