struct x
{
char a : 1; // statement 1
char c : 3; // statement 2
};
what will be the size if this structure. What is the meaning of statement 1 and 2?
Those statements declare Bit fields.
It means a
occupies memory of 1
bit and c
occupies memory of 3
bits.
The size of the structure will be:
Atleast 4 bits
+ padding(bits)
And Most likely, it will be 8 bits
i.e: 1 byte
Because,
If a series of bit fields does not add up to the size of an int, padding can take place. The amount of padding is determined by the alignment characteristics of the members of the structure.
What are Bit Fields?
From IBM documentation:
Both C and C++ allow integer members to be stored into memory spaces smaller than the compiler would ordinarily allow. These space-saving structure members are called bit fields, and their width in bits can be explicitly declared. Bit fields are used in programs that must force a data structure to correspond to a fixed hardware representation and are unlikely to be portable.
The syntax for declaring a bit field is as follows:
>>-type_specifier--+------------+--:--constant_expression--;--->< '-declarator-'
A bit field declaration contains a type specifier followed by an optional declarator, a colon, a constant integer expression that indicates the field width in bits, and a semicolon. A bit field declaration may not use either of the type qualifiers, const or volatile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With