This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Faulty if statement evaluation

Colleagues,

I was surprised today when an if() statement failed to execute as expected. In the code below when parameter 'a' is 0x00 or 0, the if statement should always evaluate as true. It does not, and instead the 'else' statement is evaluated.

I am using uVision v3.53 and executing on an NXP LPC2368 which is ARM7 TDMI.

unsigned char TestStrange ( unsigned char a )
{
   INT16 i;
   unsigned char b = 0;
   for(i=0; i<8; i++)
   {
      if( ((a) >> (7 - i)) & 0x01 == 0)
         b = 0xFF;
      else
         b = 0x0F;
   }
   return(b);
}

A work around is to evaluate the contents of the if() ahead of time, as shown below.

unsigned char TestStrange         ( unsigned char a )
{
   INT16 i;
   unsigned char c, b = 0;
   for(i=0; i<8; i++)
   {
      c = ((a) >> (7 - i)) & 0x01;
      if( c == 0)
         b = 0xFF;
      else
         b = 0x0F;
   }
   return(b);
}

Does anyone know why this is happening?

Thank you,

  • The & is a lower priority than ==
    The parenthesis below highlight what the compiler is doing

    unsigned char TestStrange ( unsigned char a )
    {
       INT16 i;
       unsigned char b = 0;
       for(i=0; i<8; i++)
       {
          if( ((a) >> (7 - i)) & (0x01 == 0))
             b = 0xFF;
          else
             b = 0x0F;
       }
       return(b);
    }
    

    try this

    unsigned char TestStrange ( unsigned char a )
    {
       INT16 i;
       unsigned char b = 0;
       for(i=0; i<8; i++)
       {
          if( (((a) >> (7 - i)) & 0x01) == 0)
             b = 0xFF;
          else
             b = 0x0F;
       }
       return(b);
    }
    

  • Yes, you are correct. You have a faulty if statement.

    Is there any difference between the following two?

    if( ((a) >> (7 - i)) & 0x01 == 0)
    

    and

    if( ((a >> (7 - i)) & 0x01) == 0)
    

    I don't know why you think you need parentheses around a variable name - it is already an atomic primitive.

    Have you checked the precedence rules for all operators you use in your expression?

    Look at this table, and see if something seems a bit strange in relation to your if statement:
    www.difranco.net/.../op-prec.htm

    Notice that == is above & in the table?

    To reduce your expression a bit:

    if (0 & 0x01 == 0) ...
    


    is evaluated as

    if (0 & (0x01 == 0)) ...
    


    which can be reduced to

    if (0 & 0) ...
    


    further reduced to

    if (0) ...
    

  • Aha! That works.

    Good to know.

    Thanks Robert.

  • Per,

    The extra () were and artifact of the function I orignially had the problem with.

    And yes, it was an operator precedence issue. I didn't realize == evaluated before &.

    Thanks,