c++ - Size of a structure having unsigned short ints -
i surfing in 1 of our organisational data documents , came across following piece of code.
struct { unsigned short int i:1; unsigned short int j:1; unsigned short int k:14; }; int main(){ aa; int n = sizeof(aa); cout << n; }
initially thought size 6 bytes size of unsigned short int 2 bytes. output of above code 2 bytes(on visual studio 2008).
is there slight possibility i:1
, j:1
, k:14
makes bit field or something? guess , not sure it. can please me in this?
yes, bitfield
, indeed.
well, i'm not sure in c++
, butc99
standard, per chapter 6.7.2.1 (10):
an implementation may allocate addressable storage unit large enough hold bit-field. if enough space remains, bit-field follows bit-field in structure shall packed adjacent bits of same unit. if insufficient space remains, whether bit-field not fit put next bits or overlaps adjacent units implementation-defined. order of allocation of bit-fields within unit (high-order low-order or low-order high-order) implementation-defined. alignment of addressable storage unit unspecified.
that makes structure size (1 bit + 1 bit + 14 bits) = 16 bits = 2 bytes.
note: no structure padding considered here.
edit:
as per c++14
standard, chapter §9.7,
a member-declarator of form
identifieropt attribute-specifier-seqopt: constant-expression
specifies bit-field; length set off bit-field name colon. [...] allocation of bit-fields within class object implementation-defined. alignment of bit-fields implementation-defined. bit-fields packed addressable allocation unit.
Comments
Post a Comment