2

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

gsamaras
  • 71,951
  • 46
  • 188
  • 305
stanleyli
  • 1,427
  • 1
  • 11
  • 28
  • 2
    Bitfields are non-portable. –  Jan 26 '17 at 00:43
  • @Neil Butterworth: They are about as non-portable as almost everything else in those parts of C++ language that deal with representations of fundamental types. – AnT stands with Russia Jan 26 '17 at 01:07
  • @An No, they are much less portable . –  Jan 26 '17 at 01:17
  • @Neil Butterworth: The only thing that's deliberately non-portable about bit-fields is their memory layout. Which is something nobody cares about since it has nothing to do with the purpose and proper use of bit-fields. The set of representable values (which is what this question is about) is, on the other hand, a completely different story: it is currently underspecified in C++ standard, but this is simply a defect of the standard. Future revisions will specify this (http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1943) – AnT stands with Russia Jan 26 '17 at 01:22

1 Answers1

0

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.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765