Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum size of a bit field in C or C++? [duplicate]

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

like image 396
templatetypedef Avatar asked Jan 27 '13 23:01

templatetypedef


People also ask

What is bit field in C?

Bit Fields in C Language In programming terminology, a bit field is a data structure that allows the programmer to allocate memory to structures and unions in bits in order to utilize computer memory in an efficient manner.

How do you calculate the size of a bit field?

In above student structure size of the structure without bit field is size of (StdId) + size of (Age) = 8 bytes + 8 Bytes = 16 bytes. After using bit fields to its members, it is 8 bits + 4 bits = 12 bits = 1.5 bytes which is very much less. Hence we can save lot of memory.

Can we have an array of bit fields?

No, you can't. Bit field can only be used with integral type variables.

How are bit fields stored in memory?

Again, storage of bit fields in memory is done with a byte-by-byte, rather than bit-by-bit, transfer.


1 Answers

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.

like image 174
icktoofay Avatar answered Oct 06 '22 01:10

icktoofay