views:

133

answers:

3

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

 bool result = false;
 bool b1 = false;
 bool b2 = false;

 ...

 if ( b1 ^ b2 )
 {
    result = true;
 }
+4  A: 

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.

Mark Rushakoff
+9  A: 

I would prefer the much clearer:

if ( b1 != b2 )
 {
    result = true;
 }
anon
+1 Fantastic :)
AraK
Depends on the context. If you're trying to do an XOR then that's what you should write.
Peter Alexander
@Peter The XOR operator is for manipulating bits. There is generally no reason for doing such manipulations with bools.
anon
Cool. Perfect xor replacement for bools.
SigTerm
or simply result = (b1 != b2)
Alexandre C.
@Alexandre: that's not quite the same. The original retains the previous value of `result` if `b1==b2`, but this doesn't.
Jerry Coffin
@Alex: `result |= (b1 != b2);`
KennyTM
A: 

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)

mb14
It's too rusty. A `bool` can be either `true` or `false`, and `true ^ true == false`. Bitrepresentations are (as usual) up to the compiler.
MSalters
I'm sure they are still old C++ compiler somewhere which have this behavior ;)
mb14