I was doing this question based on output.The code is depicted below. struct s { unsigned a:5; unsigned b:5; unsigned c:5; unsigned d:5; }v={1, 2}; main() { printf("size of v = %d",sizeof(v)); return 0; } The output of above code is "size of v = 4". I will be glad if someone could help how we are getting this 4 as output?Thanks in advance!
Auto comment: topic has been updated by codeforrest (previous revision, new revision, compare).
Auto comment: topic has been updated by codeforrest (previous revision, new revision, compare).
How exactly the memory is allocated is compiler dependent. In this case the compiler assignes the first 20 bits to the four variables, and then fills it up with 12 empty bits, just to get a nice number. Computer processors are optimized for handling 1/ 2/ 4 / 8 byte integers, so this makes more sense than creating a 3 byte type.
Btw, is it really that hard to format code in a nice way?
Thanks for prompt reply! I haven't posted code in formatted way, previously.I have corrected now formatting.
Auto comment: topic has been updated by codeforrest (previous revision, new revision, compare).
Actually if 15 bits only are needs as follows, and the bit fields are declared using
unsigned short
, then thesizeof
operator should return 2 (bytes), i.e. 16 bits.If the same bit fields are declared using
unsigned char
, then thesizeof
operator should return 3 (bytes), i.e. 24 bits, as the three bit fields are aligned to three consecutive bytes.Check the output of the following test program