Search code examples
clogical-operatorslogical-orlogical-and

Chaining logical operators


I have some trouble chaining logical operators. I'm certain that I'm messing something up but I do not see it.

I have tried various combinations of this (like adding parentheses around every "not equal to" operation etc.):

if (a != b && (a != EOF || b != EOF)) {
    /* Do stuff */
}

But nothing works. a and b are bits read from a file with fgetc, I can provide more code. But since this is about chaining logical operators I assume that this is enough.

If it's not apparent, I want the if condition execute if a and b are different but not when one of them equals EOF.


Solution

  • Translating what you said to code:

    // I want the if condition execute:
    // if    a and b are different    but  not when one of them equals EOF
       if (  a != b                   &&   !   (a == EOF || b == EOF) )
    

    Then applying DeMorgan's rule which moves the NOT inside and switches the OR to an AND:

       if ( a != b  &&  a != EOF && b != EOF )