Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of the given structure

Tags:

c++

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?

like image 568
Arvind Avatar asked Nov 06 '11 08:11

Arvind


1 Answers

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.

like image 195
Alok Save Avatar answered Nov 15 '22 11:11

Alok Save