0

I have found the following example:

#include <stdio.h> 
  
// Space optimized representation of the date 
struct date { 
    // d has value between 1 and 31, so 5 bits 
    // are sufficient 
    unsigned int d : 5; 
  
    // m has value between 1 and 12, so 4 bits 
    // are sufficient 
    unsigned int m : 4; 
  
    unsigned int y; 
}; 
  
int main() 
{ 
    printf("Size of date is %lu bytes\n", sizeof(struct date)); 
    struct date dt = { 31, 12, 2014 }; 
    printf("Date is %d/%d/%d", dt.d, dt.m, dt.y); 
    return 0; 
}

The results are

Size of date is 8 bytes
Date is 31/12/2014

I cant understand the first result. Why is it 8 bytes?

My thoughts: y is 4 bytes, d is 5 bits and m is 4 bits. The total is 4 bytes and 9 bits. 1 byte is 8 bits, then the total is 41 bits.

  • 4
    The answer is alignment. For efficiency reasons, the compiler aligns values to efficient boundaries. This will save the CPU from having to do all kinds of additional operations. – Cheatah Dec 14 '20 at 12:17
  • The smallest unit are bytes, so 8 digits -> 8 bytes – ralf htp Dec 14 '20 at 12:19
  • The layout and ordering of bit-fields is entirely implementation-defined. Without specifying your OS and compiler down to the exact versions, no answer is possible. – Andrew Henle Dec 14 '20 at 12:20
  • @Cheatah, ok, we can optimize the space using bit fields. but how? why is it equal 8 bytes? how was it computed? – Noel Miller Dec 14 '20 at 12:28

1 Answers1

1

There is a very good explanation here

C automatically packs the above bit fields as compactly as possible, provided that the maximum length of the field is less than or equal to the integer word length of the computer. If this is not the case then some compilers may allow memory overlap for the fields whilst other would store the next field in the next word (see comments on bit fiels portability below).

IrAM
  • 1,720
  • 5
  • 18