I'm looking at a legacy embedded project with the C30 compiler from microchip for a 16bit MCU. There is an expected case where the index wraps around from 0xFF which I thought would be pre-defined behavior. However the following code always dumps me in //sad :(
when I expect to end up in happy.
unsigned char index = 0xFF;
unsigned char check = 0x02;
if(check == index +3){
//happy!
}else{
//sad :(
}
Now if I specifically cast it to an unsigned char
:
unsigned char index = 0xFF;
unsigned char check = 0x02;
if(check == (unsigned char) index +3){
//happy!
}else{
//sad :(
}
It works and I end up in //happy!
So what have I missed? Is this just compiler dependent behavior?
The cause are integer promotions.
Whenever an integer type could be represented by an int
in an expression the type is promoted to int
.
In the first case index
is promoted to type int, then the addition happens and you get the value 258, which does not equal to 2.
In the second case the expression should be (unsigned char)( index +3 )
since the cast has precedence but perhaps the compiler is smart enough to figure it out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With