Logical XOR operator in C++?

后端 未结 11 1285
轮回少年
轮回少年 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 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 
    
    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;
    }
    

提交回复
热议问题