Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C unsigned char unexpected behavior on overlflow

Tags:

c

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?

like image 702
confused Avatar asked Apr 26 '16 15:04

confused


1 Answers

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.

like image 200
2501 Avatar answered Oct 04 '22 15:10

2501