C unsigned char unexpected overflow behavior

I am looking at a legacy embedded project with a C30 microchip compiler for a 16-bit MCU. There is an expected case where the index goes around 0xFF, which, as I thought, will be determined by default. However, the following code always resets me to //sad :( when I expect it to end happily.

 unsigned char index = 0xFF; unsigned char check = 0x02; if(check == index +3){ //happy! }else{ //sad :( } 

Now, if I specifically applied it to an unsigned char :

 unsigned char index = 0xFF; unsigned char check = 0x02; if(check == (unsigned char) index +3){ //happy! }else{ //sad :( } 

This works, and I end up with //happy! So what did I miss? Is this just compiler dependent behavior?

+6
source share
1 answer

The reason is whole promotions.

Whenever an integer type can be represented by an int in an expression, the type is promoted to int .

In the first case, index promoted to int type, then the addition occurs, and you get a value of 258, which is not 2.

In the second case, the expression should be (unsigned char)( index +3 ) , since the cast takes precedence, but perhaps the compiler is smart enough to understand it.

+7
source

All Articles