-4

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?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 1
    This is a bit fields. Size is 16 bit. This question is very wide and have been explained a lot of times in the books. โ€“ VP. Dec 16 '14 at 14:06
  • 3
    You guessed correctly, this is syntax for bitfields. You could have easily verified that by checking the reference for bitfields in c or c++. โ€“ eerorika Dec 16 '14 at 14:13

1 Answers1

5

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.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261