Chaining logical operators

418 Views Asked by At

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.

4

There are 4 best solutions below

0
On BEST ANSWER

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 )
0
On

To expand upon what dbush said in a comment, you want to "do stuff" if a is different to b, and a is not EOF, and b is not EOF. That is most simply expressed in code as

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

(Bear in mind that EOF is a negative value, which cannot be stored in an unsigned variable.)

0
On

try ( a!=b && a != EOF || a!=b && b!= EOF )

0
On

When you have a problem to write a condition then at first try to write a condition for which the sub-statement of the if statement will be bypassed.

For your if statement the false condition will look like

a == b || a == EOF || b == EOF

then use its negation

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

Now it can be rewritten like

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

that in turn will look like

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