1

For example ,for these similar codes when I'm writing it like the first pattern the condition gets true and in the second pattern the condition gets false.

I have watched the values of mask & (bits >> i) and mask in real-time in the debugger tool and although they were the same the condition returned false.

Why this weird behavior happening?

1:

void printLetters(unsigned int bits, unsigned int i) // 0<i<7
{
   unsigned int mask = 0x1;
   unsigned temp;

   temp = mask & (bits >> i);
   if (temp == mask) //the same condition in other way
        printf("true");
}

2:

void printLetters(unsigned int bits, unsigned int i) // 0<i<7
{
   unsigned int mask = 0x1;

   if (mask & (bits >> i)== mask) //the same condition in other way
       printf("true");`
}
Oran Sherf
  • 39
  • 9
  • What values are being passed into `bits` and `i`? – Miket25 Jun 10 '18 at 20:53
  • It seems that to get true printed out they can be only `bits=1` and `i=0`. – Frankie_C Jun 10 '18 at 20:55
  • 1
    Because in 2. `mask & (bits >> i)` needs to be in parentheses for operator precendence. So `(mask & (bits >> i)) == mask`. But in 1. the operator precedence wasn't an issue because `mask & (bits >> i)` goes into a variable first. Example 2. is effectively `if (mask & ((bits >> i)== mask))` – Weather Vane Jun 10 '18 at 20:55
  • The comparison operator `==` has higher precedence that the bitwise and operator `&` – Frankie_C Jun 10 '18 at 20:58

1 Answers1

2

The equal operator == precedence is higher than that of the bitwise AND operator &.

In the first case the temporary variable temp gets the corrected value and the successive comparison give correct result.

In the second example the comparison happen before, than the comparison result is anded bitwise with the mask.

Because the comparison gives only 1 or 0 for true or false respectively, if the bit 0 of (bits >> i) is set the result will always be true (with mask==0x1) and false else.

The code to work must use parenthesis to change the order of evaluation as below:

void printLetters(unsigned int bits, unsigned int i) // 0<i<7
{
   unsigned int mask = 0x1;

   if ( (mask & (bits >> i)) == mask) //note brackets
       printf("true");`
}
Frankie_C
  • 4,764
  • 1
  • 13
  • 30