Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does the expression 'x != 0 || x != 1' with x = 0 evaluates as if x != 0 ? – c programming

I was trying to reproduce the logic NOT gate in c as a practice, but ran into an issue I do not understand.

To make sure to have only 0 or 1 as intake, I evaluate the value of an int variable called ‘number’ using the following expression: if (number != 0 || number != 1). The idea behind that is to return -1 when number is different from 0 or 1, and to return the inverted value of the intake overwise.

For example, if number = 0 then return 1, if number = 1 then return 0, if number = 2 then return -1.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However, this expression evaluates as true even when number = 0 or number = 1. I made a shorter version of my code without the functions to test a few things and try to understand the issue, as can be seen below, but ran into the same issue. Below is my test code:

int main (void)
{
        int test = 0;

        printf("enter number\n");
        scanf("%d", &test);

        if (test != 0 || test != 1)
        {
                printf("Not 0 nor 1\n");
        }
        else
        {
                printf("0 or 1\n");
        }

        return 0;
}

When I enter ‘0’ or ‘1’, it returns ‘Not 0 nor 1’. The odd thing is that when I only test if (number != 0), it evaluates as I expect it to work (if number is 0, then the statement evaluates as false).
Is there an aspect of the OR statement I do not understand well ? Can this statement be used this way ?

>Solution :

The expression test != 0 || test != 1 is always true.

The logical OR operator evaluates to 1 i.e. true if either operand evaluates true. So the possible cases are:

  • test equals 1: the left side condition test != 0 will be true so the whole condition is true
  • test equals 0: the right side condition test != 1 will be true so the whole condition is true
  • test equals another value: both sides are true, so the whole condition is true.

So the above condition is true in all cases.

What you want is for the condition to be true IF test is not 0 AND test is not 1:

if (test != 0 && test != 1)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading