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,
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,