Subtracting unsigned ints in C and getting -Wconversion warnings

  • A+
Category:Languages

Consider:

uint16_t x; uint16_t y;  y = 0; x = y - 1; 

X will be some insane number. See other SO articles for the "why" and to learn about 2's compliment.

(I'm not asking why this is the case. I know why. I'm asking something else. Read on.)

If you turn on the gcc flag -Wconversion, this perfectly valid C code above will throw conversion to ‘uint16_t {aka short unsigned int}’ from ‘int’ may alter its value That's the compiler trying to help us not mess up. And I tend to program with such warnings turned on because they help me avoid messing up.

However, there are realistic cases where we might use an unsigned int as a counter and want to subtract 1 and NOT get this warning. Also, we want to use it as a counter, get it down to zero and then just stop. To do this in C, we have to put in some kind of a check. However, that kind of check code will run foul of the gcc warning.

Like the code above.

I want my cake and I want to eat it too.

What's the elegant solution for this?

 


Explicitly cast y-1 to uint16_t. GCC is complaining not about the subtraction, but that you might lose information after the result of the expression is assigned to a (now smaller) type. (Integral operands are silently promoted to int when used in expressions, when the types are smaller and at least one of the operands is signed.)

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: