Mircea Ionica
Mircea Ionica

Reputation: 87

Comparison between signed and unsigned warning

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?

Upvotes: 0

Views: 2643

Answers (2)

user1270973
user1270973

Reputation:

(a-b) doesn't guarantee it's unsigned since b can be bigger than a.

That's why you are getting the warning

Upvotes: 0

CB Bailey
CB Bailey

Reputation: 791939

In this expression a-b, integer promotions will apply which mean that a and b are likely to be promoted to int and the result of the expression will also be int which is why you get the warning when comparing against 8U which has type unsigned int.

The promotion would only be to unsinged int rather than int if int couldn't hold all the values of unsigned short which would only happen on platforms where int was the same size as short.

When comparing against (unsigned char)8U, the unsigned char will also be promoted to int which is why the warning doesn't happen in this case.

Upvotes: 5

Related Questions