Reputation: 6140
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?
Upvotes: 10
Views: 1055
Reputation: 213276
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".
Upvotes: 3
Reputation: 1988
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 w/o warnings with gcc 4.8.4 (gcc -Wall -Wconversion byte.c)
Hope that helps.
Upvotes: -1