Search code examples
c++gccvisual-c++warningsbit-fields

Large integer implicitly truncated to unsigned type


I was trying to determine the largest possible value in a bit field, what I did is:

using namespace std;

struct A{
    unsigned int a:1;
    unsigned int b:3;
};

int main()
{
   A aa;
   aa.b = ~0U;
   return 0;
}

MSVC is fine but GCC 4.9.2 gave me a warning:

warning: large integer implicitly truncated to unsigned type [-Woverflow]  

Wondering how I can get rid of it (Assuming I don't know the bit width of the field, and I want to know what's the largest possible value in it).


Solution

  • You can try working around this as follows

    aa.b = 1;
    aa.b = -aa.b;
    

    Note that value-representation aspects of bit-fields, including their range, are currently underspecified in the language standard, which is considered a defect in C++ standard. The is strange, especially considering that other parts of the document (e.g. specification of enum types) attempt to rely on the range of representable values of bit-fields for their own purposes. This is supposed to be taken care of in the future.