开发者

Is there anything that prevents this form of use of XOR test?

开发者 https://www.devze.com 2023-01-06 13:06 出处:网络
Is there anything that prevents this form of use of XOR test? bool result = f开发者_开发百科alse;

Is there anything that prevents this form of use of XOR test?

 bool result = f开发者_开发百科alse;
 bool b1 = false;
 bool b2 = false;

 ...

 if ( b1 ^ b2 )
 {
    result = true;
 }


I would prefer the much clearer:

if ( b1 != b2 )
 {
    result = true;
 }


No, that's perfectly acceptable (if you spell false correctly in bool b2 :]).

#include <iostream>

int main()
{
    if (false ^ false)
    {
        std::cout << "false ^ false" << std::endl;
    }

    if (true ^ false)
    {
        std::cout << "true ^ false" << std::endl;
    }
}

Output: true ^ false

Of course, in the example you've provided, you could also do result = x1 ^ x2 as shorthand.

The other question here is whether there was something preventing you from trying this yourself.


I'm not sure that's a good idea. The ^ is a bitwise operator not a logical one. So 1^2 = 3. I'm a bit rusty in C++ but I think bool are stored as unsigned char or something so

bool a= 1
bool b = 2

is valid.

a == true; // yes
b == true; // yes
a ^ b == true; // yes.  not what you are expecting :-(

To be sure to use proper true/false values, you have to do something like (!!a) ^ (!!b)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号