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,

Parents Reply Children
No data