Paul Sen
Paul Sen

Reputation: 554

Bit-fields at two separate locations in a Structure in C

In a structure we normally have contiguous bit-fields; that is, one after the other and adjacent to each other — for example:

struct demo
{
  char a;
  char b:1;
  char c:2;
  char d:2;
  int  e;  
} demo1;

The size of demo1 will be 8 bytes:

Now consider following structure:

struct demo
{
  char a;
  int  b:1;
  char c;
  char d;
  int  e:2;
} demo1;

When I use sizeof(demo1), it gives me 8 bytes — but I want to know how these bit-fields are presented in memory.

If calculated like above structure size should be:

During programming we don't bother about this thing that how size will be calculated using sizeof and we even don't use bit-fields at two different locations, but sometimes this type of question is asked by interviewers.

Upvotes: 0

Views: 979

Answers (1)

ameyCU
ameyCU

Reputation: 16607

Consecutive (non-zero width) bit-fields can be merged into a single memory location, while a bit-field followed by a non-bit-field are distinct memory locations.

 struct demo
 {
      char a;
      int b:1;
      char c;
      char d;
      int  e:2;
 } demo1;

So in this struct, there is 1 non bit-field and 1 bit-field and then 2 non bit-fields and finally a bit-field.

Having a non-bit-field (or a zero-length bit-field) right after a bit-field member, what follows next will be a different/independent memory location/object.

And also:

A compiler does not reorder the elements of a struct, because that would violate the C standard. Section 6.7.2.1 of the C99 standard states:

Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared.

Upvotes: 4

Related Questions