Logical XOR in C/C++? - Page 2
 CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com

# Thread: Logical XOR in C/C++?

1. Junior Member
Join Date
May 2013
Posts
2

## Re: Logical XOR in C/C++?

Originally Posted by NMTop40
your best way to do it would be

(!b1 ^ !b2)

where b1 and b2 are expressions.
This does not implement XOR. Try substituting b1<-0, b2<-0
You can also see it in the xor karnaugh map which cannot be simplified

simplest way is to use bitwise ^ or (!b1&&b2)||(b1&&!b2)

cheers!

2. Elite Member Power Poster
Join Date
Jan 2006
Location
Singapore
Posts
6,734

## Re: Logical XOR in C/C++?

Originally Posted by juncode
This does not implement XOR. Try substituting b1<-0, b2<-0
If we use the rules from C: (!(-1) ^ !(-2)) = (0 ^ 0) = 0. This is correct.

Originally Posted by juncode
You can also see it in the xor karnaugh map which cannot be simplified
I do not see how that matters here since the proposed alternative expression is not a simplification.

Originally Posted by juncode
simplest way is to use bitwise ^
It was already pointed out that this would not work in general, back in post #4, some 12 years ago.

3. Junior Member
Join Date
May 2013
Posts
2

## Re: Logical XOR in C/C++?

Of course. I confused ^ with &&. Clearly !bn gives a result of type bool, which can be then correctly used with bitwise xor ^.

Sorry and thanks for pointing that out!

4. Elite Member Power Poster
Join Date
Apr 2000
Location
Belgium (Europe)
Posts
4,626

## Re: Logical XOR in C/C++?

It depends how you define 'correctly'
the result of 2 bools being bitwise xor'ed is an int. if you expect the result being of type bool, then you may not be getting the result you want. the "correctest" approach for logical xor behaviour is really using a != operator.
with != either of the 2 operators is evaluated exactly once, and the result is a bool.

Using a != will probably also better convey what the code is supposed to do, making it more readable. The only exception I can think of to this is probably trying to actually model logic gates in a circuit.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•