bleat interteiment
bleat interteiment

Reputation: 1459

True AND False or False AND True type of condition in a more elegant way?

I'm not really sure how to be specific about this question within the title and I know this is probably really stupid question to ask, but still ... :D

Is there any better way to check this type of condition:

if (bool1 && !bool2) {
  #different code1    
  #samecode
}
else if (!bool1 && bool2)
{
  #different code2
  #samecode
}

In this example, some parts of the code should be checked to meet these conditions, but some should work in. Contradicting statements doesn't allow me to merge them under one condition. Is there any other way to write down this condition, so that I don't have to copy/paste code?

Upvotes: 1

Views: 467

Answers (1)

41686d6564
41686d6564

Reputation: 19641

If your objective is to avoid repeating #samecode, you may make use of the Exclusive OR (AKA, XOR) operator as follows:

if (bool1 ^ bool2) // <-- If bool1 is true or bool2 is true but not both.
{
    if (bool1)
    {
        // #different code1
    }
    else
    {
        // #different code2
    }
    // #samecode
}

Upvotes: 6

Related Questions