Logical XOR operator in C++?

后端 未结 11 1241
轮回少年
轮回少年 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:10

    Here is how I think you write an XOR comparison in C++:

    bool a = true;   // Test by changing to true or false
    bool b = false;  // Test by changing to true or false
    if (a == !b)     // THIS IS YOUR XOR comparison
    {
        // do whatever
    }
    

    Proof

    XOR TABLE
     a   b  XOR
    --- --- ---
     T   T   F
     T   F   T
     F   T   T
     F   F   F
    
    a == !b TABLE
     a   b  !b  a == !b
    --- --- --- -------
     T   T   F     F
     T   F   T     T
     F   T   F     T
     F   F   T     F
    

    The proof is that an exhaustive study of inputs and outputs shows that in the two tables, for every input set the result is always the identical in the two tables.

    Therefore, the original question being how to write:

    return (A==5) ^^ (B==5)
    

    The answer would be

    return (A==5) == !(B==5);
    

    Or if you like, write

    return !(A==5) == (B==5);
    

提交回复
热议问题