Reputation: 8564
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?
Upvotes: 4
Views: 325
Reputation: 339786
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.
Upvotes: 6
Reputation: 12596
How about this?
if(isCorrect(a) != isCorrect(b))
{
//problem
}
else
{
//not a problem
}
You can use XOR also, but != works fine and is more readable if you are dealing with boolean values, IMO.
Upvotes: 1
Reputation: 8170
simply:
if (isCorrect(a) == isCorrect(b))
{
// a AND b are both correct or incorrect
} else {
// a OR b is incorrect
}
Upvotes: 2
Reputation: 12510
if (isCorrect(a) != isCorrect(b)) {
// a OR b is incorrect
} else {
// a AND b are correct or incorrect
}
Upvotes: 6