Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using typecasting to remove gcc compiler warnings

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:

  1. Why is it bad to use typecasts in this way?
  2. Do I lose anything by simply omitting -Wconversion and letting the compiler do implicit conversions for me?
like image 609
bitsmack Avatar asked Sep 11 '15 16:09

bitsmack


People also ask

How do I get rid of GCC warnings?

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.

How do I turn off compiler warnings?

To turn off the warning for a specific line of code, use the warning pragma, #pragma warning(suppress : 4996) .

Which option of GCC inhibit all warning messages?

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

Which GCC flag is used to enable all compiler warnings?

gcc -Wall enables all compiler's warning messages. This option should always be used, in order to generate better code.


1 Answers

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.

like image 56
Jens Gustedt Avatar answered Oct 07 '22 14:10

Jens Gustedt