I was surfing in one of our organisational data documents and I came across the following piece of code.
struct A {
unsigned short int i:1;
unsigned short int j:1;
unsigned short int k:14;
};
int main(){
A aa;
int n = sizeof(aa);
cout << n;
}
Initially I thought the size will be 6 bytes as the size of the unsigned short int is 2 bytes. but the output of the above code was 2 bytes(On visual studio 2008).
Is there a slight possibility that the i:1
, j:1
and k:14
makes it a bit field or something? Its just a guess and I am not very sure about it. Can somebody please help me in this?
Yes, this is bitfield
, indeed.
Well, i'm not very much sure about c++
, but In c99
standard, as per chapter 6.7.2.1 (10):
An implementation may allocate any addressable storage unit large enough to hold a bit-field. If enough space remains, a bit-field that immediately follows another bit-field in a structure shall be packed into adjacent bits of the same unit. If insufficient space remains, whether a bit-field that does not fit is put into the next bits or overlaps adjacent units is implementation-defined. The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined. The alignment of the addressable storage unit is unspecified.
That makes your structure size (1 bit + 1 bit + 14 bits) = 16 bits = 2 bytes.
Note: No structure padding is considered here.
Edit:
As per C++14
standard, chapter §9.7,
A member-declarator of the form
identifieropt attribute-specifier-seqopt: constant-expression
specifies a bit-field; its length is set off from the bit-field name by a colon. [...] Allocation of bit-fields within a class object is
implementation-defined. Alignment of bit-fields is implementation-defined. Bit-fields are packed into some addressable allocation unit.