I have two variables:
unsigned short a,b;
/* When I compare them with a magic number like this */
if (a > 8U) /* all fine*/
/* But when I make the following comparison: */
if ((a-b) > 8U) /* warning: comparison between signed and unsigned*/
/* And when I make the following comparison: */
if ((a-b) > ((unsigned char)8U)) /* all fine again */
Do you have any ideas why I get the warning ?
Does this have anything to do with integer promotion maybe?
In this expression
a-b, integer promotions will apply which mean thataandbare likely to be promoted tointand the result of the expression will also beintwhich is why you get the warning when comparing against8Uwhich has typeunsigned int.The promotion would only be to
unsinged intrather thanintifintcouldn’t hold all the values ofunsigned shortwhich would only happen on platforms whereintwas the same size asshort.When comparing against
(unsigned char)8U, theunsigned charwill also be promoted tointwhich is why the warning doesn’t happen in this case.