What is an elegant way to show an XOR statement

c, c#, java, syntax

Solution

You can use ^ as the others have suggested, however be careful as it is also a bitwise exclusive or. The exact behaviour as to when it will be used for bitwise and when it will be used for logical vary by language and by data types.

For example in Java make sure that A and B are boolean types and you will be fine.

In c though if you did for ints `i` and `j`;

if (i ^ j) {
}

Then it would do a bitwise xor on i and j and then if the result of that is 0 the result would be handled as false, otherwise true.

In Java that would give you a syntax error as the result of the expression is not boolean.

Some alternatives that do work:

C/C++:

(!i ^ !j) 
// The ! converts i to boolean.
// It also negates the value but you don't need to reverse it back as you are comparing the relative values

C#/Java:

(A ^ B)
// Make sure A or B are boolean expressions, you will get a compile time error if they are not though.

Problem

What is a short and concise (and readable!) way to make sure a conditional follows the conditions: `If a is true, then run code.` `If b is true, then run code.` `If both a and b is true, then do NOT run code.` One way is Nested: ``` if (a || b) { if(!(a && b)) { //Code } } ``` This is verbose, but perhaps more easily communicates the intention? We can make it slightly shorter by: ``` if((a||b) && (!a&&b)) ``` But that is slightly cryptic, especially if the variable names are long. Am I missing something? Is there a better way to write the above?

Original source