In a program I am trying to check two boolean values (returned from a function); the condition that needs to be checked is:
- only if any one of the returned value is true and the other is false then I have a problem;
- else if both are true or false I am good to go to next step.
Which of the following two examples would be the efficient way to check the condition, or is there a better solution?
a and b are integer values on which I am checking a condition for correctness in isCorrect
function and it return true or false.
1.
// checking for the correctness of both a and b
if ((isCorrect(a) && !isCorrect(b)) ||
(!isCorrect(a) && isCorrect(b)))
{
// a OR b is incorrect
}
else
{
// a AND b are both correct or incorrect
}
2.
// checking for the correctness of both a and b
if (! (isCorrect(a) ^ isCorrect(b)))
{
// a OR b is incorrect
}
else
{
// a AND b are correct or incorrect
}
Thanks,
Ivar
P.S: code readability is not an issue. EDIT: I meant to have an XOR in the second option. Also, I agree with the == and != options, but what if I had to use boolean operators?
if (isCorrect(a) != isCorrect(b)) {
// a OR b is incorrect
} else {
// a AND b are correct or incorrect
}
Your test doesn't need boolean operators, just this:
if (isCorrect(a) == isCorrect(b)) {
// they both have the same value
} else {
// they don't ...
}
EDIT - I deliberately didn't use the same comments to reflect that the primary purpose of the comment should be to describe the intent, and not the specific implementation. In this case the simplest statement of intent is that both a
and b
obtained the same result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With