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:
#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
CodePudding user response:
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.