Logical XOR operator in C++?

后端 未结 11 1192
轮回少年
轮回少年 2020-11-29 15:54

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         


        
相关标签:
11条回答
  • 2020-11-29 15:57

    The != operator serves this purpose for bool values.

    0 讨论(0)
  • 2020-11-29 15:57

    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.

    0 讨论(0)
  • 2020-11-29 15:57

    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.

    0 讨论(0)
  • 2020-11-29 16:02
    #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!)

    0 讨论(0)
  • 2020-11-29 16:04

    Use a simple:

    return ((op1 ? 1 : 0) ^ (op2 ? 1 : 0));
    
    0 讨论(0)
  • 2020-11-29 16:07

    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;
    }
    
    0 讨论(0)
提交回复
热议问题