Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolving conversion warnings with compound assignment operators

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?

like image 694
c0dehunter Avatar asked Nov 14 '14 07:11

c0dehunter


Video Answer


1 Answers

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".

like image 103
Lundin Avatar answered Nov 15 '22 01:11

Lundin