Bitwise and "&" question

Hello!

Why do the following if comparisons show different results?

unsigned int i = 0;
unsigned int test = 0;
void setup() {
  Serial.begin(115200);
  for ( i=0; i<4; i++ ) {
    Serial.println( i&3 );
    test = i&3;
    if ( i&3==0 ) {
      Serial.println( "zero" );         // not show
    }
    if ( test==0 ) {
      Serial.println( "test is zero" ); // show
    }
  }
}
void loop() {
  delay(10);
}
/* Serial print results:
0
test is zero
1
2
3
*/

Take a look at the C++ operator precedence table and think about what it means for the above logical construction.

Hint: if in doubt, use parentheses to enforce your intent.

( (i&3)==0 )
That solved it!
Thank you very much!

Do you not have your Compiler Warnings (in Preferences...) turned up to "All"? If you did so you would have gotten the helpful message:

sketch_oct09a.ino: In function 'void setup()':
sketch_oct09a.ino:10:16: warning: suggest parentheses around comparison in operand of '&' [-Wparentheses]
     if ( i & 3 == 0 )
              ~~^~~~

That means "The '3 == 0' comparison is one side of your 'i & something' expression and that's often a mistake. You should put parens around the '3 == 0' part, to let people know you really mean it."

if(i & 3 == 0)

The referred Table says that the "equality operator" has the higher precedence. If so, will the Compiler attempt to evaluate "3 == 0" or will just ignore with an error message?

There is nothing wrong with expression if(i & 3 == 0). 3==0 is evaluated first, leading to the observed and sometimes unexpected result.

1 Like

The warning just tells you it is unusual and may not be what you meant. The compiler will continue on and do what you told it to.

That is why I always turn on all warnings and use parentheses when I am not sure (it saves looking up the rules).

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.