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

Variable changing value in loop "IF" without correctly condition

I want know why me variable test change to 1, considering that I don’t have a sequence like:
0 or 255 > 0 or 255 > 0 or 255 > 0 or 255

Why my if condition doesn’t working?

I have this code:

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

#include <stdio.h>

int main()
{

  int item[4]={1,2,3,4};
  int test =0;

  printf("test: %d\n", test);
int i =0;
            if( (item[i] == 0 || 255) && (item[i+1] == 0 || 255) && (item[i+2] == 0 || 255)  &&
             (item[i+3] == 0 || 255) && (item[i+4]== 0 || 255))
              {
                test =1;
              }
                   

  printf("test after if:%d\n\n\n",test);
}

result:

test: 0 test after if:1

I want result test after if = 0 because my condition is: sequence 0 or 255 4 times

>Solution :

Because of operator precedence the expression

item[i] == 0 || 255

is equivalent to

(item[i] == 0) || 255

That means the condition is true if item[i] == 0 is true, or if 255 is true. And because 255 is not 0 (0 is the only integer value that is false) it’s true, making your whole condition true.

Since all the sub-conditions in your if are the same, you have (basically) true && true && true && true. Which is, of course, true.

To check if an element is 0 or 255 you need to check the element twice:

item[i] == 0 || item[i] == 255

Modify all your sub-conditions similarly.

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