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

if statement isn't executing when a mask is applied to a variable even tough it should

In my example im creating an integer variable called testVar and i make it equal to a1 in hex. when printing out the variable it shows that it should indeed be equal to a1 in hex. Now when checking if testVar is equal to a1 in an if statement, the if statement only executes when there is no mask applied to the variable.

My question "is why these if statements don’t execute when the variable has a mask applied to it?".

 #include <stdio.h>
int testVar = 0xa1;   //testVar should equal 0x000000a1 now

void main(){
    printf("%x \n",testVar);               //should prove that testVar is indeed equal to a1 in hex
    printf("%x \n",testVar & 0x000000ff);  //both printf functions are outputting a1
    
    
    if (testVar == 0x000000a1){      //this if statement works!
        printf("success1");      
    }
    if (testVar & 0x000000ff == 0x000000a1){      //this doesn't execute
        printf("success2");      
    }
    if (testVar & 0x000000ff == 0xa1){      //this doesn't execute
        printf("success3");      
    }
}

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

>Solution :

The equality operator == has higher precedence than the binary bitwise-AND operator &. That means that this:

if (testVar & 0x000000ff == 0x000000a1)

Parses as this:

if (testVar & (0x000000ff == 0x000000a1))

Which is not what you want. Use parenthesis to ensure proper grouping:

if ((testVar & 0x000000ff) == 0x000000a1)

And similarly:

if ((testVar & 0x000000ff) == 0xa1)
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