Force GCC to report a warning when casting a float pointer to int pointer?

Viewed 218
void foo(uint32_t* p);

...
float32_t* x;
foo( (uint32_t*)x );

A static code analysis tool reports a “casting from float* to integer*" problem.

How do I force GCC compiler to report the same warning?

Compiler optins are: -pedantic -Wall -Wextra -Wconversion

2 Answers

By using an explicit conversion (a "cast"), you have told the compiler: "I definitely want to do this". That's what a cast means. It makes little sense for the compiler to then warn about it.

Instead, rely on implicit conversions, and if you try to use one that is not valid, the compilation of your program will fail until you fix it.

Now, that only helps you while you're writing your program. It doesn't help you statically analyse poorly-written code that already exists, for the purpose of improving the code. Well, that's okay! That's what your, er, static analyser is for, as you've already discovered.

All that being said, if you have strict aliasing enabled, the compiler will perform a little static analysis of its own and may kick out a warning here, if there's a risk that your program won't work as you wanted. But strict aliasing is often disabled in GCC builds and, even when it's not, detecting aliasing violations is complicated and cannot be guaranteed.

I doubt you will find the compiler option you're looking for. (In my opinion, the compiler option you're looking for should not exist.)

The usual question is:

I'm doing something weird. I know it's okay, but the compiler keeps warning about it. How do I disable the warning?"

Now, if the "something weird" you're doing is mixing and matching incompatible pointers in potentially unsafe ways, the way to disable the warning is often: use an explicit cast.

So what you're asking, in effect, is a way to re-enable a warning which you (or someone) has already disabled by using an explicit cast, a cast which you now believe is wrong, after all.

We're on the cusp of an infinite regress here. If there were a way to warn about questionable conversions requested by explicit casts, next week we'd be getting this question:

I'm using a special conversion between nominally-incompatible pointers. I know it's okay, but the compiler keeps warning about it, even though I'm using an explicit cast. How do I disable the warning? Do I need to use two casts?"

It's kind of like warning messages. Suppose you try to delete a vital system file. Suppose your computer pops up a warning dialog saying "About to delete vital file. Confirm?" Suppose you decide you don't want to delete it, but you accidentally click the "OK" button, and the file goes away. Do you find yourself wishing that the warning dialog had been followed by a second dialog asking, "Are you really sure?" You might, but most people will probably agree that having to click "OK" twice whenever they delete a file would be an unacceptable nuisance...

Related