I am doing embedded ARM programming with gcc 4.9. I've been using the -Wconversion
switch because it's in my company's default dev tool configuration. I'm using the stdint.h types (uint8_t, uint32_t, etc).
The compiler creates warnings every time I perform a compound assignment or even simple addition. For example:
uint8_t u8 = 0;
uint16_t u16;
// These cause warnings:
u8 += 2;
u8 = u16 >> 8;
The "common method" to fix this is to use casts, as discussed here and here:
u8 = (uint8_t)(u8 + 2);
u8 = (uint8_t)(u16 >> 8);
In addition to this being ugly, I keep running into convincing evidence that casting is generally bad practice.
My questions:
-Wconversion
and letting the compiler do implicit conversions for me?To answer your question about disabling specific warnings in GCC, you can enable specific warnings in GCC with -Wxxxx and disable them with -Wno-xxxx. From the GCC Warning Options: You can request many specific warnings with options beginning -W , for example -Wimplicit to request warnings on implicit declarations.
To turn off the warning for a specific line of code, use the warning pragma, #pragma warning(suppress : 4996) .
-Wno-coverage-invalid-line-number can be used to disable the warning or -Wno-error=coverage-invalid-line-number can be used to disable the error. Suppress warning messages emitted by #warning directives.
gcc -Wall enables all compiler's warning messages. This option should always be used, in order to generate better code.
The compiler is showing you potential problem spots, that you should consider changing, but not by casts. The problem in the code that you have is that in C, arithmetic is never done on type that are narrower than int
: the compiler always performs an implicit conversion to int
for them.
So effectively your code is converting the narrow unsigned types to int
, does the operation and then converts them back to the unsigned type.
Generally doing arithmetic with narrow types is not a good idea. Only use them if storage size is a problem (usually that would be larger structures such as arrays). For local, more or less temporary variables these narrow types make no sense.
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