Home > Software design >  Disable GCC narrowing conversion errors
Disable GCC narrowing conversion errors

Time:08-13

I have code from over 20 years in C/C and one technique used to handle variable data sizes was to let automatic type conversion handle it.

For example:

#define MY_STATUS_UNDEFINED (-1)

Then if it was compared/used against a int64_t it was auto expanded to -1LL, for uint64_t to 0xFFFFFFFFFFFFFFFF, for uint32_t to 0xFFFFFFFF, int16_t to -1, uint16_t to 0xFFFF, etc..

However, now I'm getting errors with the newer gcc versions that complain about narrowing conversion. In this case it was a switch statement with a UINT variable.

switch (myuint) {
  case MY_STATUS_UNDEFINED: 
    break;
}

What is the recommended way to get it to not error out?

What is the easiest way to get it to not error out?

What is the cleanest way so it doesn't error out and doesn't give any warning message?

Essentially, I want it to do the auto type conversion properly but no warning or errors.

CodePudding user response:

Using the following brief example:

#include <cstdint>
#include <iostream>

#define MY_STATUS_UNDEFINED (-1)

void bar()
{
    std::cout << "It works\n";
}

void foo(uint32_t n)
{
    switch (n) {
    case MY_STATUS_UNDEFINED:
        bar();
        break;
    }
}

int main()
{
    foo(0xFFFFFFFF);
    return 0;
}

You are seeing the following error from gcc:

error: narrowing conversion of ‘-1’ from ‘int’ to ‘unsigned int’ [-Wnarrowing]

Now, pay careful attention to the error message. gcc is telling the exact option to shut this off. See the [-Wnarrowing] annotation? That's the compilation flag that's responsible for producing this error message.

To turn it off, stick a "no-" in front of it:

-Wno-narrowing

All gcc diagnostics use this convention. Now the shown code will compile, run, and produce the expected result:

It works!

Add -Wno-narrowing to your global compilation options.

You should really consider this to be only a temporary band-aid solution. These compilation errors are exactly what you want. They're telling you about real or potential problems. -Wall -Werror -Wsuggest-override -Wreturn-type are my favorite compilation options.

  • Related