Signed and Unsigned Pitfalls

Consider the following code:

int fn(int x, unsigned int factor) {
	return x / factor;
}


int main(void)
{
 int x=-20,y=10,res;

 res = fn(x,y);
 printf("y=%d\n",res);

 return 0;
}

the function divide -20 by 10 and return the result , expect to get -2 as a result but it prints:

y=429496727

its a weird pitfall because the function get signed int and we send -20 and unsigned int and we send 10. It looks ok but the divide cannot perform on different types so the unsigned int is converted to int (big number because msb=1) and we get a wrong result

 

Conclusion

Do not perform operations on different types without explicit casting