At our company we have a policy to compile with -Wconversion
which produces some conversion warnings. While I do agree this extra checking prevents bugs, it is annoying to see warnings on shorthand operators such as in the following case:
uint8_t byte;
byte += 8; // conversion to 'uint8_t' from 'int' may alter its value [-Wconversion]
Now this can be solved by rewriting it as byte = (uint8_t)(byte+8)
which in turn reduces code readability.
Is there any better way to do this?
Consider the reason why you get the warning, namely that the integer constant 8
is of type int
. That everything in C has to be promoted to (signed) int
is a well-known design flaw of the language.
Suppose you had byte += 256;
or byte += -1;
or byte += function_that_returns_int();
. All of them are potentially severe bugs, so the warning certainly makes sense to enable.
There's really no other work-around than to cast the result of the operation to the intended type, uint8_t
. Which isn't necessarily a bad thing, as it creates self-documenting code saying "yes, I have actually considered which types that are used in this calculation so there should be no overflows".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With