13

Possible Duplicate:
struct bitfield max size (C99, C++)

Is there a limit to the number of bits that I can specify in a bit field in C or C++? For example, could I do this:

struct HugeInt {
    int myInt: 1000;
};

I'm asking about both C and C++, since I know that the language specs sometimes differ and wanted to see if the above example was guaranteed to work / not work in C or C++.

Community
  • 1
  • 1
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • Isn't this same as this one? http://stackoverflow.com/questions/2647320/struct-bitfield-max-size-c99-c – P.P Jan 27 '13 at 23:53
  • @KingsIndian- Yes, you are correct. I missed that one the first time around! – templatetypedef Jan 27 '13 at 23:54
  • Alright. voted to close. I recently read the other one :) – P.P Jan 27 '13 at 23:57
  • @KingsIndian- I also voted to close this. :-) I'm usually much better about avoiding duplicate questions. – templatetypedef Jan 27 '13 at 23:58
  • What do you want 1000 bit integers for?! Perhaps you should look at gmp (**G**NU **M**ulti**p**recision library), http://gmplib.org. Many GNU tools, like bc(1) use it to handle big integers. – vonbrand Jan 28 '13 at 00:03
  • 1
    @vonbrand- This was purely asked out of curiosity. I'm aware that there are good libraries for long bitfields and for high-precision integers. – templatetypedef Jan 28 '13 at 00:05

2 Answers2

16

In C11, section 6.7.2.1, clause 4:

The expression that specifies the width of a bit-field shall be an integer constant expression with a nonnegative value that does not exceed the width of an object of the type that would be specified were the colon and expression omitted. If the value is zero, the declaration shall have no declarator.

So in short, it must be between zero and the size of the type if it had not had a bit-field part.

icktoofay
  • 126,289
  • 21
  • 250
  • 231
  • As seen in the answer from the original question, in C++ it is legal to do this, but in doing so the extra bits are pretty much ignored. – templatetypedef Jan 28 '13 at 00:02
  • How are we to know the width of the object? – David G Jan 28 '13 at 00:05
  • @David: `sizeof(type) * CHAR_BIT` where `type` is your type, which must be a qualified or unqualified version of one of `_Bool`, `signed int`, `unsigned int`, or some other implementation defined-type. – icktoofay Jan 28 '13 at 00:10
0

size of bit-field 'myInt' (1000 bits) cannot exceed size of its type (int, usually 32 bits)

Emanuele Paolini
  • 9,912
  • 3
  • 38
  • 64