In Objective-c, safe and good way to compare 2 BOOL values? In Objective-c, safe and good way to compare 2 BOOL values? objective-c objective-c

In Objective-c, safe and good way to compare 2 BOOL values?


Comparing two boolean values should be handled with an XOR operation.

Trying to compare the two booleans directly is a misuse of the fundamentals of Boolean Algebra:http://en.wikipedia.org/wiki/Boolean_algebra_(logic)

When you are doing

BOOL a = (b == c);

then this value may return false even if both b and c are true. However the expression b && c will always return YES if both b and c are true, i.e. greater than 0, and NO otherwise.

Instead this is what you are actually trying to do:

BOOL xor = b && !c || !b && c;BOOL equal = !xor;

equivalent with

BOOL equal = !(b && !c || !b && c);

or

BOOL equal = (b && c) || (!b && !c)

If you have to spend time making sure that your BOOL values are normalized (i.e. set to either 1 or 0) then your doing something wrong.


It's perfectly valid to use bool in Objective-C as it's part of the C99 standard (ยง7.16). In my opinion it's also the best way to handle safe comparisons of boolean types.

The only reason not to use bool everywhere is that BOOL is omnipresent in Objective-C and the frameworks.


apart from the other answers, I would like to note that comparing bools for equality is not a very common operation. BOOL is not a type, it's just a macro which hides the fact that booleans are only integers. For every boolean operation, you should rather use programming structures and operators that can handle integers as booleans correctly:

e.g: if (condition1 == NO) {} should be if (!condition1) {}

if (condition1 == condition2) {}
can be
if ((condition1 && condition2) || (!condition1 && !condition2)) {}
or better
BOOL newCondition = (condition1 && condition2) || (!condition1 && !condition2);if (newCondition) {}

The shortest way to write a condition doesn't have to be the best way.