Enabling Conversion Alerts with Compound Assignment Operators

In our company, we have a policy for compiling with -Wconversion , which issues some conversion warnings. Although I agree that an additional check prevents errors, it is annoying to see warnings about abbreviated statements, for example, 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, will reduce the readability of the code.

Is there a better way to do this?

+6
source share
2 answers

Consider the reason why you receive a warning, namely that the integer constant 8 is of type int . That everything in C needs to be upgraded to (signed) int is a well-known flaw in language design.

Suppose you had byte += 256; or byte += -1; or byte += function_that_returns_int(); . All of them are potentially serious errors, therefore the warning certainly makes sense to include.

In fact, there is no other work than to cast the result of the operation to the supposed type uint8_t . This is not necessarily bad, because it creates self-documenting code saying "yes, I really looked at the types that are used in this calculation, so there should be no overflows."

+1
source

This may not exactly solve your problem, but at least gives you a hint that there is a solution for almost everything.

 #include <stdio.h> #include <stdint.h> #define SAFE_ADD(a,b) ((a) = (typeof(a))((a)+(b))) int main(void) { uint8_t byte = 0; SAFE_ADD(byte, 8); fprintf(stderr, "byte = %d \n", byte); return 0; } 

Compiled without warning with gcc 4.8.4 (gcc -Wall -Wconversion byte.c)
Hope this helps.

-1
source

Source: https://habr.com/ru/post/978174/


All Articles